Axios features and features:
- Create XMLHttpRequests from the browser
- Create HTTP requests from Node.js
- Support PromiseAPI
- Intercept requests and responses
- Transform request data and response data
- Cancel the request
- Automatically convert JSON data
- The client supports XSRF defense
Install axois in your project
The use of NPM
npm install axios --save
Copy the code
Use the CDN
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Copy the code
Use the demo
-
When executing the GET mode, if the request parameters are carried, the request parameters can be in two ways:
axios.get('/user? ID=12121').then((response) = > { //response }).catch((error) = > { //error}); Or axios. Get ('/user', {params: { ID: 12121 } }).then((response) = > { //response }).catch((error) = > { //error }); Copy the code
-
Performing a POST request
axios.post('/user', {name: '12121' }).then((response) = > { //reponse }).catch((error) = > { //error }); Copy the code
-
Execute multiple concurrent requests
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()]).then(
axios.spread(function (acct, perms){
// Both requests are now completed}));Copy the code
All of the above is written using axios.get/post, which is a little bit more cumbersome. You can create the request by passing the configuration through Axios. The default request mode for Axios is GET.
axios({
url: apiURL,
method: method,
timeout: timeout,
data: data,
params: params,
headers: {
'Content-Type': 'application/json'.'token': window.sessionStore.getItem('token') | |' '}});Copy the code
When dealing with concurrent modes:
- axios.all(iterable)
- axios.spread(callback)
Axios also supports creating an AXIOS example through a custom configuration
Grammar: axios. Create (/ config)
var instance = axios.create({
baseURL: 'https://some-domain.com/api/'.timeout: 1000.headers: {'X-Custom-Header': 'foobar'}});Copy the code
Related request configuration
These are the configuration options you can use when creating a request. Only urls are required. If method is not specified, the request uses the get method by default.
//'url' is the URL used to request the server
url: '/user'.//'method' is the method used to create the request
method: 'get'.// The default is get
//'baseUrl' is automatically appended to 'url' unless '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 you to modify request data before sending it to the server
// Can only be used for put, POST, and patch requests
// The function in the following array must return a string, either an ArrayBuffer, or a Stream
transformRequest: [function (data){
// Perform any conversion on data
returndata; }].//'transformResponse' allows modification of response data before passing then/catch
transformResponse: [function (data){
// Perform any conversion to data
returndata; }].//'headers' is the 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 sent as the body of the request
// Apply only to these request methods (PUT, POST, 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: {
name: '1212'
},
// '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./ / the 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 said the server response data type, can be a arraybuffer, blob, document, json, text, stream
responseType: 'json'.Copy the code
Response of the structure
The response to a request contains the following information:
{
// '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: {}
}
Copy the code
In the actual development process, the background interface will follow the RESTful specification and encapsulate the return format of the data itself, for example, the following format:
That is to say, the data we extract is obtained from Response. data and then obtained in a certain format. Generally, the encapsulation format of background data is as follows:
Create a new util package:
MessageEntity class:
package com.ssm.util;
import lombok.Data;
@Data
public class MessageEntity<T> {
private Integer code;
private String msg;
private T data;
private Integer total;
}
Copy the code
MessageCode class:
package com.ssm.util;
public enum MessageCode {
SYSTEM_CODE(500."System error");
private Integer code;
private String message;
public Integer getCode(a) {
return code;
}
public String getMessage(a) {
return message;
}
MessageCode(Integer code, String message) {
this.code = code;
this.message = message; }}Copy the code
ResultForma class:
package com.ssm.util;
public class ResultFormat {
public static MessageEntity success(a) {
return success(null);
}
public static <T> MessageEntity<T> success(T t){
MessageEntity msg = new MessageEntity();
msg.setCode(200);
msg.setMsg("Operation successful");
msg.setData(t);
return msg;
}
public static MessageEntity error(MessageCode message) {
MessageEntity msg = new MessageEntity();
msg.setCode(message.getCode());
msg.setMsg(message.getMessage());
returnmsg; }}Copy the code
Configure default Values
- The global AXIOS default value
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 the default value of the configuration when creating the instance
var instance = axios.create({
baseURL: 'https://api.example.com'
});
// Change the default value after the instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
Copy the code
- Configuration priority
Configurations are merged in a priority order. The order is: the library defaults found in lib/defaults.js, then the instance defaults property, and finally the requested Config parameters. The latter will take precedence over the former. Here’s an example:
// 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
Intercepts requests or responses before they are processed by THEN or catch.
// 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);
});
Copy the code
If you want to remove interceptors later, you can do this:
var myInterceptor = axios.interceptors.request.use(function () {/ *... * /});
axios.interceptors.request.eject(myInterceptor);
Copy the code
cancel
The cancel token can be created using the canceltoken. source factory method like this:
var CancelToken = axios.CancelToken;
var source = CancelToken.source();
axios.get('/user/12345', {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// Processing error}});// Cancel the request (the message argument is optional)
source.cancel('Operation canceled by the user.');
Copy the code
Axios source code learning
Find the lib/axios.js file under axios
Lib /axios.js
// lib/axios.js
function createInstance(defaultConfig) {
// Create an Axios instance
var context = new Axios(defaultConfig);
/ / the following code can also be implemented: var instance = Axios. Prototype. Request. Bind (context);
// Instance refers to the request method, and the context refers to the context, so it can be called directly with instance(option)
// axios.prototype. request specifies the datatype of the first parameter, which allows us to call instance(URL, option)
var instance = bind(Axios.prototype.request, context);
// Extend the axios.prototype method to instance,
// So instance has get, post, put, etc
// Specify the context as context so that when the method on the Axios prototype chain is executed, this points to the context
utils.extend(instance, Axios.prototype, context);
// Extend the context object's own properties and methods to instance
// Note: Because the forEach method that extends internally does for in traversal of the object, it traverses only properties of the object itself, not properties on the prototype chain
// In this case, instance has the defaults and interceptors attributes. (These two properties will be covered later)
utils.extend(instance, context);
return instance;
}
// Take the default configuration items as parameters (described below) and create an Axios instance, which will eventually be exported as an object
var axios = createInstance(defaults);
Copy the code
-
The interceptor interceptors
Interceptors are divided into request interceptor (interceptors.request) and response interceptor (interceptors.response).
Request interceptors.request intercepts each or a specified HTTP request and modifies configuration items.
Interceptors. Response refers to the intercepting of HTTP requests after they are received, and the return items can be modified.
-
Data converter
Data converters are divided into request converters and response converters. As the name implies, a request converter (transformRequest) converts data before a request, and a response converter (transformResponse) converts data after a response.
-
HTTP request adapter
-
The config configuration items
The flow chart of axios
Axios can be used in several ways:
- The first way of use:
axios(option)
axios({
url,
method,
headers,
})
Copy the code
- The second way of use:
axios(url[, option])
axios(url, {
method,
headers,
})
Copy the code
- The third way of use (for
The get, delete
Etc.) :axios[method](url[, option])
axios.get(url, {
headers,
})
Copy the code
- The fourth way of use (for
Post, put,
Etc.) :axios[method](url[, data[, option]])
axios.post(url, data, {
headers,
})
Copy the code
- The fifth way of use:
axios.request(option)
axios.request({
url,
method,
headers,
})
Copy the code
User configuration item object config
HTTP request adapter, request address, request method, request header, request data, transformation of request or response data, request progress, HTTP status code verification rules, timeout, request cancellation, etc. As you can see, almost all axios functionality is configured and passed through this object, both as a communication bridge within the AXIOS project and between users and AXIOS.
import axios from 'axios'
// First: directly modify the defaults property on Axios instances, mainly to set the general configuration
axios.defaults[configName] = value;
// Type 2: the axios.prototype. request method is eventually called when the request is made, and the configuration item is passed in, mainly to set the "case" configuration
axios({
url,
method,
headers,
})
// Create a new instance of Axios and pass in the configuration item
let newAxiosInstance = axios.create({
[configName]: value,
})
Copy the code
Cookies are carried across domains
import axios from 'axios'
axios.defaults.withCredentials = true;
Copy the code
Use simple encapsulation with AXIos in react projects
Name three files api.js, apiurl.js, and apiip.js, where apiip.js is used to get the server IP address, apiurl.js is used to assemble the IP address and interface path, of course, this can be implemented using baseURL, also can be: axios.defaults.baseURL = ‘api.example.com’;
The realization of the Api. Js
import axios from 'axios';
import {notification} from 'antd';
import * as ApiURL from 'src/HttpClientRequest/ApiURL';
const key = 'keepOnlyOne';
/** * data request public method * @param apiURL Interface request path * @param configObj Parameters passed in by the user to configure * @returns {Promise
} */
function getDataFromServer(apiURL, configObj) {
// Get the interface configuration parameters passed in by the user
let {
method = 'get',
data = {},
timeout = 3000,
params = {}
} = configObj;
return new Promise(function (resolve, reject) {
axios({
url: apiURL,
method: method,
timeout: timeout,
data: data,
params: params,
headers: {
'Content-Type': 'application/json'.'token': window.sessionStore.getItem('token') | |' '
}
}).then((response) = > {
if (response) {
if (response.data && response.data.code) {
resolve(response);
} else {
notification.error({
key,
message: 'Operation failed'.description: 'Wrong data format'}); resolve(response); }}else {
notification.error({
key,
message: 'Operation failed'.description: 'Server error'
});
resolve(response);
}
}).catch((error) = > {
notification.error({
key,
message: 'Operation failed'.description: 'Network exception, please try again later'
});
reject(error);
});
});
}
export function login(configObj) {
return getDataFromServer(ApiURL.LOGIN, configObj);
}
Copy the code
ApiURL.js
import API_IP from './ApiIp';
// Address of the login interface
export const LOGIN = `${API_IP}/index/login`;
Copy the code
ApiIp.js
// Get the current browser address
const interfaceIp = window.location.host;
const imageAddrassIp = window.location.hostname;
// Get the protocol of the current browser
const browserProtocol = window.location.protocol;
// Encapsulate the server request address
const serverInterfaceIp = `${browserProtocol}//${interfaceIp}`;
const serverImageIp = `${browserProtocol}//${imageAddrassIp}`;
// Request address provided externally (compatible with production and development environments)
export const API_IP = process.env.NODE_ENV === 'development' ? 'http://121.0.0.1:8080' : serverInterfaceIp;
export const IMAGES_IP = process.env.NODE_ENV === 'development' ? 'http://121.0.0.1' : serverImageIp;
Copy the code
Reference article: juejin.cn/post/684490…