NPM download
npm install axios
Get request with query parameter form
axios.get('/user? ID=12345')
.then( function(response){// Return data console.log(response); }) .catch(function(error) {console.log(error)}).finally(function(){// for final processing});Copy the code
Get requests in the form of params arguments
axios.get('/user', {
params: {
ID: 123
}
})
.then( function (response){
console.log(response);
})
.catch( function (error) {
console.log(error);
})
.finally( function(){// Final processing})Copy the code
Make get requests with async/await mode
async function getUser(){
try {
const response = await axios.get('user? ID=123');
console.log(response)
} catch (error) {
console.log(error)
}
}Copy the code
Making a POST request
axios.post('/user', {
firstName: 'Fred',
lastName: 'Find'
})
.then( function (response){
console.log(response);
})
.catch( function (error) {
console.log(error);
})Copy the code
Get is slightly different from POST
Request methods are different
The two request methods are different. The data information carried in the GET request is the header that places the request information and can be displayed explicitly through the URL, while the data information carried in the POST request is placed in the body of the request information.
Parameter modes are different
Axios issues a Get request with {} as the second argument, which contains a parms object
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.then(function () {
// always executed
}); Copy the code
Axios makes a Post request, and the second argument is an object
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});Copy the code
Make multiple requests simultaneously
function getUser() {
return axios.get('/user/1234');
}
function getUserPermissions() {
return axios.get('/user/1234/permissions');
}
axios.all([getUser(),getUserPermissions()])
.then( axios.spread( function(userResp, permResp){console.log(userResp, permResp){console.log(userResp, permResp){console.log(userResp, permResp){console.log(userResp, permResp){console.log('UserInfo',userResp);
console.log('permissionInfo',permResp);
}))
.catch (functionConsole. log(error); });Copy the code
Initiate a request in the form of a configuration
axios({
method: 'post',
url: '/user/1234',
data: {
firstName: 'Fred',
lastName: 'Find'
}
}).then( function (response) {
console.log(response);
})Copy the code
Sets the type of data to return
axios({
method: 'get',
url: 'http://bit.ly/2mTM3nY',
responseType: 'stream'
})
.then( functionResponse.data.pipe (fs.createWritestream ()) {// Use node.js syntax here // pipe the returned data to the fs module create file response.data.pipe(fs.createWritestream ())'a.jpg'));
});Copy the code
Axios defaults to get requests
Axios instance
Const instance = axios.create({// Default request path baseUrl:'http://some-domain.com/api/', // Timeout: 1000, // Customize headers: {'X-Custom-Header': 'foobar'}}Copy the code
Request API reading
{// Request url url:'/user'// The default method is get method:'get'// http://baidu.com/user baseUrl:'http://baidu.com/'. // This method can only be used for PUT, POST, PATCH, and DELETE methods // The data type returned by the pretreatment must be string or Buffer or ArrayBuffer // You can also define request headers transformRequest: [function(data, headers) {// Perform data processing herereturndata; }], // The data is preprocessed before returning the data.function (data) {
returndata; }], // make a custom request headers: {'X-Requested-With': 'XMLHttpRequest'}, // URL parameter params: {ID: 1234}, // serialize the requested parameter paramsSerializer:function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})}, // Request body data: {firstName:'Fred'}, // Set the request timeout period. If the request timeout period is longer than the timeout period, the request will be interrupted. Timeout: 1000 // The default value is 0 and will never timeoutfalse/ / set totrueWhen the request is sent with cookie withCredentials:false// Customize the request adapter:function(config) {} // HTTP basic authentication and provide credentials auth: {username:'janedoe',
password: 's00pers3cret'}, // Data return type // arrayBuffer, document, json, text, stream, default json responseType:'json'// Return the encoding type responseEncoding:'utf8', // XSRF cookie for XSRF tooken xsrfCookieName:'XSRF-TOKEN', // default // XSRF name for XSRF tooken xsrfHeaderName:'X-XSRF-TOKEN'// default // Upload progress processing event onUploadProgress:function(progressEvent) {// Do whatever you want with the native progress event}, // Download progress event onDownloadProgress:function(progressEvent) {// Do whatever you want with the native progress event}, // maxContentLength: 2000, // Return Http Code for the response // Return Http Code validateStatus regardless of success or failure:function (status) {
returnstatus >= 200 && status < 300; // redirect: directs: directs: directs: directs: directs: directs: directs: directs: directs HttpAgent: new http.Agent({keepAlive:true }),
httpsAgent: new https.Agent({ keepAlive: true}), // set proxy: {host:'127.0.0.1',
port: 9000,
auth: {
username: 'mikeymike',
password: 'rapunz3l'}, // cancelToken: new cancelToken (function (cancel) {
})
}Copy the code
Reponse related interpretation
Data: {}, // The status code returned by the server is status: 200, // the status of the returned information statusText:'OK'Headers: {}, // config: {}, // `request` is the request that generated this response // It is the last ClientRequest instancein node.js (in redirects)
// and an XMLHttpRequest instance in the browser
request: {}
}Copy the code
The instance
axios.get('/user/12345')
.then(function (response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});Copy the code
Set the axiOS global default configuration
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
Configured after the axiOS instance
const instance = axios.create({
baseURL: 'https://api.example.com'
});
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;Copy the code
The interceptor
Interception and processing before a request is made or data is returned
Request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});Copy the code
Response interceptor
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});Copy the code
Remove interceptors
const myInterceptor = axios.interceptors.request.use(function() {/ *... * /}); axios.interceptors.request.eject(myInterceptor)Copy the code
Create interceptors using axios instances
const instance = axios.create();
instance.interceptors.request.use(function() {/ *... * /});Copy the code
Error handling
axios.get('/user/12345')
.catch(function (error) {
if(error.response) {// The request has been sent, but the return status code is not within 2xx console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); }else if(error.request) {// The request was made and no response was received // 'error.request' is an instance of XMLHttpRequestin the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else{// What error was triggered before the configuration request console.log('Error', error.message);
}
console.log(error.config);
});Copy the code
Error range of the status code returned by validateStatus configuration
axios.get('/user/12345', {
validateStatus: function (status) {
return status < 500; // Reject only if the status code is greater than or equal to 500
}
})Copy the code
Cancel the request
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
axios.post('/user/12345', {
name: 'new name'}, {cancelToken: source.token}) // Execute cancel request source.cancel('Operation canceled by the user.');
Copy the code
Cancels the request by passing an executor in the CancelToken constructor
const CancelToken = axios.CancelToken;
let cancel;
axios.get('/user/12345', {
cancelToken: new CancelToken(function executor(c) {
// An executor function receives a cancel functionas a parameter cancel = c; })}); // cancel the request cancel();Copy the code
Data parameters are formatted into Application/X-www-form-urlencoded
URLSearchParams
const params = new URLSearchParams();
params.append('param1'.'value1');
params.append('param2'.'value2');
axios.post('/foo', params);Copy the code
qs
const qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123}));Copy the code
ES6
import qs from 'qs';
const data = { 'bar': 123}; const options = { method:'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
data: qs.stringify(data),
url,
};
axios(options);Copy the code
Node.js
const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));Copy the code