The reference documentation adds some interpretation of its own
An overview of the
Axios is an HTTP library based on promises
Essentially, XMLHttpRequests requests are Ajax requests
features
- Create XMLHttpRequests from the browser
- Create HTTP requests from Node.js
- Supporting Promise API
- Intercept requests and responses
- Transform request data and response data
- Cancel the request
- Automatically convert JSON data
- The client supports XSRF defense
Browser support, Internet Explorer 8 or later
The basic use
Axios provides two different forms to send an HTTP request, one via the Axios () method and the other via the corresponding HTTP method provided by the Axios object, respectively, such as: axios.get() , axios.post() , axios.delete()
- axios.get(url)
- axios.post(url,data)
- axios.delete(url)
- axios.update(url)
- axios.put(url,data)
. , etc.
Methods such as axios.get() are described in official documentation as aliases for request methods
Use of the AXIos Api
The axios(config) method receives an object that contains some configuration of the request, and AXIos sends the corresponding HTTP request based on that configuration
The basic configuration items should include:
- Method Method of the request (optional: GET, POST, etc.)
- Url requested address (must)
- Data Data sent in a request (required for a request such as POST)
The default request method is GET so you don’t need to set method if it’s a GET request
// Send a POST request
axios({
method: 'post'.url: '/user/12345'.data: {
firstName: 'Fred'.lastName: 'Flintstone'}});Copy the code
In the then and catch callbacks, a normal request will enter THEN, and an exception request will enter catch
// Send a POST request
axios({
method: 'post'.url: '/user/12345'.data: {
firstName: 'Fred'.lastName: 'Flintstone'
}
}).then(res= > {
consloe.log(res)
}).catch(err= > {
console.log(err)
})
Copy the code
// Send a GET request (default method)
axios('/user/12345');
Copy the code
Personal opinion: With Axios, you just need to have a basic grasp of the Axios () API
Request the use of an alias
Request the use of an alias
Axios also provides a corresponding method for each HTTP method to send the corresponding request to send the GET request
// Create a request for the user with the given ID
axios.get('/user? ID=12345').then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
Copy the code
Send the POST request axios.post('/user', {
firstName: 'Fred'.lastName: 'Flintstone'
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
Copy the code
Other methods are used similarly, omitted
Note: When using alias methods, url, method, and data attributes do not have to be specified in the configuration.
Response of the structure
In the result of the response to a request made through AXIos, Axios adds some fields like the following
{
// 'data' is the response provided by the server
data: {},
// 'status' is the HTTP status code from the server response
status: 200.// 'statusText' is the HTTP status information from the server response
statusText: 'OK'.// 'headers' is the head of the server response
headers: {},
// 'config' is the configuration information provided for the request
config: {},
// 'request'
// `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance the browser
request: {}}Copy the code
Data is the data returned by the back end. Generally, we only need to pay attention to the data field in Response
Create an instance
You can create a new instance of AXIos using the custom configuration axios.create([config])
const instance = axios.create({
baseURL: 'https://some-domain.com/api/'.timeout: 1000.headers: {'X-Custom-Header': 'foobar'}});Copy the code
The axios() API in the created instance is changed to the Request () API in the same way as the other functions, such as the request alias, are not changed
Here are the methods owned by the instance
- request(config)
- get(url[, config])
- delete(url[, config])
- head(url[, config])
- options(url[, config])
- post(url[, data[, config]])
- put(url[, data[, config]])
- patch(url[, data[, config]])
Axios combines the config in these methods with the config specified when creating the instance
Request configuration
{
// '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
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 exclusive: Stream
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 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
Configure default Values
Axios can configure default values for some configuration items that take effect on each request
Global default value
This can be set using axios.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
Default values for custom instances
You can also set instance.defaults by creating custom objects
// 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
Configuration priority
The configuration passed in when instance axios.create() is overwritten by the value of the same configuration set in instance.defaults, and the first two are overwritten by the configuration in the specific request method
// Create the instance using the default values of the configuration provided by the library
// The default value of the timeout configuration is 0
var instance = axios.create();
// Override library timeout default value
// Now all requests wait 2.5 seconds before timeout
instance.defaults.timeout = 2500;
// Set override timeout for requests known to take a long time
instance.get('/longRequest', {
timeout: 5000
});
Copy the code
The interceptor
- Request interceptor axios. Interceptors. Request
- Axios. Interceptors. Response response interceptors
// Add request interceptor
axios.interceptors.request.use(function (config) {
// What to do before sending the request
config.header["Token"] = "xxxx"
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
if (response.status === 200) {return response.data
} else {
return Promise.reject(new Error('error'}})),function (error) {
// Do something about the response error
return Promise.reject(error);
});
Copy the code
If you want to cancel an interceptor, you can cancel it by using a variable that receives the instance returned when you set the interceptor, and then using eject
const myInterceptor = axios.interceptors.request.use(function () {/ *... * /});
axios.interceptors.request.eject(myInterceptor);
Copy the code
. To be perfect