Axios basics
Axios basic request method
Common methodsaxios(config)
//GET
axios({
method: 'get'.url: '/user/12345'.data: {
firstName: 'Fred'.lastName: 'Flintstone'}});/ * -- - * /
//POST
axios({
method: 'post'.url: '/user/12345'.data: {
firstName: 'Fred'.lastName: 'Flintstone'}});Copy the code
Shorthand GET
axios.get(url[, config])
axios.get('http://localhost:9999/user/login').then((res) = > {
console.log(res)
})
Copy the code
Short POST
axios.post(url[, data[, config]])
axios.post('http://localhost:9999/user/login', {account:123.password:123
}).then((res) = > {
console.log(res)
})
Copy the code
Create a new Axios instance
// Create a new configuration item
axios.create([config])
Copy the code
Analyzing configuration itemsconfig
{
// 'url' is the server URL used for the request
url: '/user'.// 'method' is the method used to create the request
method: 'get'.// default
// baseURL will automatically precede url unless the url is an absolute URL.
// It can facilitate passing relative urls to axios instance methods by setting a 'baseURL'
baseURL: 'https://some-domain.com/api/'.// 'transformRequest' allows request data to be modified before being sent to the server
// Only for 'PUT', 'POST', and 'PATCH' request methods
// The function in the following array must return a string, either an ArrayBuffer, or a Stream
transformRequest: [function (data, headers) {
// Perform any conversion on data
returndata; }].// 'transformResponse' allows the response data to be modified before being passed to then/catch
transformResponse: [function (data) {
// Perform any conversion on data
Return qs.stringify(data) => Account =123&password=123 */
returndata; }].// 'headers' is a custom request header to be sent
headers: {'X-Requested-With': 'XMLHttpRequest'},
// 'params' is the URL parameter to be sent with the request
// Must be a plain object or URLSearchParams object
params: {
ID: 12345
},
// 'paramsSerializer' is a function that serializes' params'
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})},// 'data' is the data that is sent as the body of the request
// Apply only to these request methods 'PUT', 'POST', and 'PATCH'
// When 'transformRequest' is not set, it must be one of the following types:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser specific: FormData, File, Blob
// - Node only: Stream default transmission format is application/json
data: {
firstName: 'Fred'
},
// 'timeout' specifies the number of milliseconds for the request to timeout (0 indicates no timeout)
// If the request takes longer than timeout, the request will be interrupted
timeout: 1000.// 'withCredentials' indicates whether credentials are needed for cross-domain requests
withCredentials: false.// default
// Adapter allows you to customize handling requests to make testing easier
// Return a promise and apply a valid response (see [Response docs](#response-api)).
adapter: function (config) {
/ *... * /
},
// 'auth' indicates that HTTP base authentication should be used and credentials provided
// This will set an Authorization header that overrides any existing custom Authorization header set using headers
auth: {
username: 'janedoe'.password: 's00pers3cret'
},
// 'responseType' indicates the data type of the server response, which can be 'arrayBuffer ', 'blob', 'document', 'json', 'text', 'stream'.
responseType: 'json'.// default
// `responseEncoding` indicates encoding to use for decoding responses
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8'.// default
// 'xsrfCookieName' is the name of the cookie used as the value of the XSRF token
xsrfCookieName: 'XSRF-TOKEN'.// default
// `xsrfHeaderName` is the name of the http header that carries the xsrf token value
xsrfHeaderName: 'X-XSRF-TOKEN'.// default
// 'onUploadProgress' allows progress events to be processed for uploads
onUploadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
// 'onDownloadProgress' allows progress events to be processed for downloads
onDownloadProgress: function (progressEvent) {
// Handling of native progress events
},
// 'maxContentLength' defines the maximum size allowed for the response content
maxContentLength: 2000.// 'validateStatus' defines a resolve or reject PROMISE for a given HTTP response status code. If 'validateStatus' returns' true' (or is set to 'null' or 'undefined'), promises will be resolved; Otherwise, the promise will be rejecte
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
// 'maxRedirects' defines the maximum number of redirects to follow in Node.js
// If set to 0, no redirection will be followed
maxRedirects: 5.// default
// `socketPath` defines a UNIX Socket to be used in node.js.
// e.g. '/var/run/docker.sock' to send requests to the docker daemon.
// Only either `socketPath` or `proxy` can be specified.
// If both are specified, `socketPath` is used.
socketPath: null.// default
// 'httpAgent' and 'httpsAgent' are used in Node.js to define custom agents to be used when performing HTTP and HTTPS, respectively. Allow configuration options like this:
// keepAlive is disabled by default
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
// 'proxy' defines the host name and port of the proxy server
// 'auth' indicates that HTTP basic authentication should be used to connect to the proxy and provide credentials
// This will set a 'proxy-authorization' header, overwriting the existing custom 'proxy-authorization' header set by using 'header'.
proxy: {
host: '127.0.0.1'.port: 9000.auth: {
username: 'mikeymike'.password: 'rapunz3l'}},// 'cancelToken' specifies the cancel token used to cancel the request
// (See the Cancellation section later for more information)
cancelToken: new CancelToken(function (cancel) {})}Copy the code
The global AXIOS default value
Use the defaults
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
Copy the code
Custom instance defaults
// Set config defaults when creating the instance
const instance = axios.create({
baseURL: 'https://api.example.com'
});
// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
Copy the code
The interceptor
Return a Promise
// Add request interceptor
axios.interceptors.request.use(function (config) {
// What to do before sending the request
return config;
}, function (error) {
// What to do about the request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// What to do with the response data
return response;
}, function (error) {
// Do something about the response error
return Promise.reject(error);
});
// Remove interceptor
const myInterceptor = axios.interceptors.request.use(function () {/ *... * /});
axios.interceptors.request.eject(myInterceptor);
Copy the code
Axios secondary encapsulation
http.js
/ * axios secondary packaging: each time based on the public portion of the axios send request to extract + axios. Defaults. XXX + axios. Interceptors. Request/response interceptor * /
import axios from 'axios';
import qs from 'qs';
import tool from './tool';
// If the request URL is not prefixed, base-URL is added by default. If the prefix is set by the user, the prefix is written by the user.
// In real development, our project has different environments "development, test, grayscale, production" : we need different base-urls for different environments
// 1) Set environment variables while compiling
$NPM I cross-env
// + package.json is processed in scripts
// development environment serve:"cross-env NODE_ENV=development vue-cli-service serve",
"Cross-env NODE_ENV=production vue-cli-service build"
// 2) Get the value of environment variable in code, set different base-URL according to different value
let env = process.env.NODE_ENV || 'development',
baseURL = ' ';
switch (env) {
case 'development':
baseURL = 'http://127.0.0.1:9999';
break;
case 'production':
baseURL = 'http://api.zhufengpeixun.cn';
break;
}
axios.defaults.baseURL = baseURL;
// A few things that can be extracted: timeouts & whether CORS is allowed to carry resource credentials across domains (e.g. Cookie)
// + withCredentials on the client :true, then the server side must also be set to allow
axios.defaults.timeout = 10000;
axios.defaults.withCredentials = true;
// POST series requests: Request body to the server, project requirements need to be URLENCODED format; In modern browsers, when we ask for the format of the body to be passed to the server, the browser automatically updates the content-Type in the request header!
axios.defaults.transformRequest = data= > {
// If the DATA we write is a pure object, it needs to be handled as required
if (tool.isPlainObject(data)) data = qs.stringify(data);
return data;
};
// Specify the status code returned by the server as a successful request
// Success: The server returns a normal response and the HTTP status code is verified by validateStatus
/ / failure:
// + The server returns information, but the HTTP status code is not verified by validateStatus
// + request timeout or request interrupt reason.code==='ECONNABORTED'
// the server did not return any message "maybe the network is down"
/ / +...
axios.defaults.validateStatus = status= > {
return status >= 200 && status < 400;
};
// Request interceptor: Inside AXIos, the config items have been processed and are intended to be intercepted before sending requests to the server based on the configuration items; The purpose of interception is to change some information in the configuration item.
axios.interceptors.request.use(config= > {
// Common requirement: The token is passed to the server through the request header every time a request is sent
const token = localStorage.getItem('token');
if (token) {
config.headers['Authorization'] = token;
}
return config;
});
// Ondepressing /onrejected, which occurs when the request succeeds/fails, and then/catch is processed in the business layer
axios.interceptors.response.use(response= > {
// Request success: Normally we return response body information
return response.data;
}, reason= > {
// Request failed: Generally we do a uniform error message
if (reason && reason.response) {
let response = reason.response;
// There is a response message, but the status code is incorrect, we do different prompts according to different status codes
switch (response.status) {
case 400:
// ...
break;
case 401:
// ...
break;
case 404:
// ...
break; }}else {
if (reason && reason.code === 'ECONNABORTED') {
// The request timed out or was interrupted
}
if(! navigator.onLine) {/ / broken network}}return Promise.reject(reason);
});
export default axios;
Copy the code
Index.js entry file
import axios from './http';
import instance from './http2';
import md5 from 'blueimp-md5';
const queryUserList = (departmentId = 0, search = ' ') = > {
return axios.get('/user/list', {
params: {
departmentId,
search
}
});
};
const setUserLogin = (account, password) = > {
password = md5(password);
return axios.post('/user/login', {
account,
password
});
};
export default {
queryUserList,
setUserLogin
};
Copy the code
Vue is mounted globally in main.js
import Vue from 'vue';
import App from './App.vue';
import api from './api/index';
Vue.config.productionTip = false;
// After each page this.$API is available
Vue.prototype.$api = api;
new Vue({
render: h= > h(App),
}).$mount('#app');
Copy the code