What is Axios?
Axios is an Ajax wrapper library based on Promises and is currently the most popular Ajax request library on the front end. Simply put, send GET and POST requests is a lightweight library that can be directly introduced when used.
Second, axios characteristics
- Asynchronous Ajax request library.
- It is available on both the browser and Node side.
- Support the Promise API.
- Support for request and response interception.
- Response data automatically converts JSON data.
- Request cancellation is supported.
- Multiple requests can be sent in batches.
- The client supports security protection against XSRF attacks.
Third, axios API
3.1, install,
/* NPM install axios */ NPM install axios --save /* bower install axios /* use yarn */ yarn add axios /* CDN import */ <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>Copy the code
Note: CDN is recommended for simple static pages.
3.2, axios API
The request is created by passing the relevant configuration parameters to AXIOS. Such as: axios (config)
// axios({method: 'post', // request method URL: '/user/12345', // access interface data: {// transmit data firstName: 'Fred', lastName: 'Flintstone' } });Copy the code
// axios({method: 'get', url: 'http://localhost:80/one',// ') 'stream'}). Then (function (response) {response.data.pipe(fs.createWritestream ('save.jpg')) // Save images});Copy the code
3.3. Axios request method
Each time the AXIos API initiates a request, it needs to set its request method and response header timeout information, which is tedious to use. For convenience, AXIos provides aliases for all supported request methods, which can be directly specified to initiate the request, and other parameters can be set globally. Such as:
axios('/user/id=1');
Copy the code
The above AXIos sends the request directly, and when the request mode is not set, the default is to use the GET request, the same as Ajax and FETCH. So a get request is sent, which can also be sent using the GET method, as shown in the following example:
axios.get(
'1.txt' ,
{
params:{id:'1'}
}
).then(res=>{
console.log(res);
})
.catch(err=>{
console.log(err);
})
Copy the code
This can be abbreviated to axios(URL,config).
Other specific methods are as follows:
axios.request(config)
axios.get( url , config)
axios.delete( url , config)
axios.head( url , config)
axios.options( url , config)
axios.post( url [,data [, config ]])
axios.put( url [,data [, config ]])
axios.patch( url [,data [, config ]])
Copy the code
3.4. Send requests in batches
Network requests tend to have multiple network requests executing concurrently, and sometimes they need to be processed together to return results, so AXIOS has concurrent processing. Axios.all () can send multiple network requests in parallel and wait for all of them to return and continue processing.
Use grammar:
// axios.all([axios.get(URL1), axios.get(URL2),]).then(res=>{console.log(res)) Res [0] is the first request data res[1] is the second request data}) /* second processing */ axios.all([axios.get(URL1), axios.get(URL2), ]. Then (axios.spread((res1,res2)=>{res1 //Copy the code
Use axios.spread to automatically split the data returned from the request.
1.5. Global Default configuration
The global default configuration is primarily applied to each request. Not only save the time of knocking code, want to modify, just modify one can be all modified.
Common global default configurations are:
Axios.defaults. baseURL = "http://localhost:8080/" // configure the domain name axios.defaults.timeout = 6000; // In milliseconds, Set the timeout head set time / * * / axios.defaults.headers.com mon [' Authorization '] = AUTH_TOKEN axios. Defaults. Headers. Post [' the content-type '] = 'application/x-www-form-urlencoded'Copy the code
3.6. Axios instances
Const instance = axios.create({baseURL: 'https://api.example.com'}); // Alter defaults after instance has been created instance.defaults.headers.common['Authorization'] = AUTH_TOKENCopy the code
We use AXIos instantiation because globally instantiated HTTP requests have global response interception. When some of our interfaces cannot return a status code, we will not get a response. In this case, we need to re-instantiate an AXIos in the current API and set a new response interception code.
3.7 interceptors
Interceptors are divided into two types, request interception and response interception, which can process certain services in a unified manner.
- Request interceptor:
/ * request interceptor Unified before sending a request to add token * / axios. Interceptors. Request. Use (config = > {config. Headers. Token = Sessionstorage. getItem("token") // Add toke return config},err=>{console.log(err)// Request error})Copy the code
- Response interceptor
Axios. Interceptors. Response. Use (response = > {return response}, err = > {the console. The log response errors (err) / /})Copy the code
3.8 Response content
In basic use, the first instance request succeeds and the result console.log(res) is printed. The result is as follows:
{data:{}, status:200, // HTTP status text returned from the server statusText:'OK', // headers: {}, //config is some configuration information at the time of request config: {}}Copy the code
4. Axios common applications
Axios can be used in both the browser side and in Node.js. XMLHttpRequest is sent in the browser and HTTP is sent in Node.js. Projects like VUE, React, Node, and so on can use Axios.