brief introduction
This paper mainly explains the concept and basic use of axios.
axios is currently one of the most popular ajax wrapper libraries for making it easy to send ajax requests.
Supported functions:
- Issue an XMLHttpRequests request from the browser.
- From node.js makes an http request.
- Supports the Promise API.
- Ability to intercept requests and responses.
- Ability to convert request and response data.
- Cancel the request.
- Implement automatic conversion of JSON data.
- Client support prevents XSRF attacks.
Start with json-server to create a simple service for ajax to send requests. json-server is a simple service that can receive restful requests.
github address: https://github.com/typicode/json-server
Step 1: Install: npm install -g json-server
Step 2: Create a db.json's file, copy the site's data into it.
{ "posts": [ { "id": 1, "title": "json-server", "author": "typicode" } ], "comments": [ { "id": 1, "body": "some comment", "postId": 1 } ], "profile": { "name": "typicode" } }
Step 3: Start command: json-server --watch db.json
Visit http://localhost:3000/posts The following page is successful
Using axios
GitHub address: https://github.com/axios/axios
For convenience, we use the fourth directly.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>axios Basic Use</title> </head> <body> <button id="btn1">Send out get request</button> <br><br> <button id="btn2">Send out post request</button><br><br> <button id="btn3">Send out put request</button><br><br> <button id="btn4">Send out delete request</button> <hr> <div>Other requests sent api:</div><br><br> <button id="btn5">Send out get Request 1</button> <br><br> <button id="btn6">Send out post Request 1</button><br><br> <button id="btn7">Send out put Request 1</button><br><br> <button id="btn8">Send out delete Request 1</button> </body> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> //Send get document.getElementById("btn1").onclick = function(){ axios({ method:"GET", url:"http://localhost:3000/posts/1" }).then(response=>{ console.log(response); }) }; //Send post document.getElementById("btn2").onclick = function(){ axios({ method:"POST", url:"http://localhost:3000/posts", data:{ title:"axios Study", author:"Yehaocong" } }).then(response=>{ console.log(response); }) }; //Send put document.getElementById("btn3").onclick = function(){ axios({ method:"PUT", url:"http://localhost:3000/posts/2", data:{ title:"axios Study", author:"Liaoxiaoyan" } }).then(response=>{ console.log(response); }) }; document.getElementById("btn4").onclick = function(){ axios({ method:"DELETE", url:"http://localhost:3000/posts/2", }).then(response=>{ console.log(response); }) }; //Other api to send requests document.getElementById("btn5").onclick = function(){ //Send get, use get, url for first parameter, config for second parameter axios.get("http://localhost:3000/posts/1") .then(response=>{ console.log(response); }) }; //Send post document.getElementById("btn6").onclick = function(){ //Send a post request, the url for the first parameter, the body for the second parameter, and the config configuration object for the third parameter axios.post("http://localhost:3000/posts", {title:"axios Learning 2", author:"Yehaocong2"}) .then(response=>{ console.log(response); }) }; //Send put, document.getElementById("btn7").onclick = function(){ //Send put, receive three parameters, url request body, config configuration object axios.put("http://localhost:3000/posts/2",{title:"axios learning ", author:"Liaoxiaoyan"}) .then(response=>{ console.log(response); }) }; document.getElementById("btn8").onclick = function(){ //Send delete request, receive 2 parameters, url config configuration object axios.delete("http://localhost:3000/posts/3") .then(response=>{ console.log(response); }) }; //This is basically the same as axios({}) // axios.request({ // }) </script> </html>
Response result structure analysis for requests:
Common configuration items for configuration objects:
{ // Path url url: '/user', // Request method, default get method: 'get', //The base url, the URL of the final request is a baseURL+url splice, so setting the default globally can make the URL when sending the request concise baseURL: 'https://some-domain.com/api/', //Set Request Header headers: {'X-Requested-With': 'XMLHttpRequest'}, //Setting the query parameter of the request url can make the url concise. //For example, the url is https://some-domain.com/api/user Then params is set as follows, and the final url is: //https://some-domain.com/api/user?ID=12345&name=Jack params: { ID: 12345, name:"Jack" }, //Set Requestor data: { firstName: 'Fred' }, //Set another format for the request, but this is a direct string setting data: 'Country=Brasil&City=Belo Horizonte', //Request timed out in milliseconds, default 0, no timeout. timeout: 1000, //Response data type, default json responseType: 'json', //Coding rules for response data, default utf-8 responseEncoding: 'utf8', //Maximum length of response volume maxContentLength: 2000, // Maximum Request Body Length maxBodyLength: 2000, //Setting the response status code is successful, call resolve, otherwise call reject fails //Default is greater than or equal to 200, less than 300 validateStatus: function (status) { return status >= 200 && status < 300; },
Default Configuration
The global default configuration can be set to avoid duplication of multiple duplicate configurations in different requests, such as baseURL, timeout, and so on, where the baseURL is set.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Default Configuration</title> </head> <body> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> axios.defaults.baseURL="http://localhost:3000"; //Since the baseURL is configured above, all we need to do for future requests is configure the url without using the full path as before axios.get("/posts/1") .then(response=>{ console.log(response); }) </script> </body> </html>
axios interceptor
Essentially, it is a function.
There are two types:
- Request interceptor: Used to intercept requests, customize them to make a logic and send them. It can be used to configure common logic without having to go through each request.
- Response Interceptor: Used to intercept a response, do some processing before starting the response callback.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>axios Interceptor</title> </head> <body> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> //This is the api that sets the request interceptor, passing in two callbacks, the first successful callback and the second failed callback. axios.interceptors.request.use( function(config){ console.log("Request Interceptor 1 call succeeded"); return config; }, function(error){ console.log("Request interceptor 1 call failed"); return Promise.reject(error) } ) //This is the api to set the response interceptor, the first successful callback and the second failed callback axios.interceptors.response.use( function(response){ console.log("Response Interceptor 1 call succeeded"); return response; }, function(error){ console.log("Response interceptor 1 call failed"); return Promise.reject(error); } ) axios.get("http://localhost:3000/posts/1") .then(function(response){ // console.log("Request Callback Succeeded"); }).catch(function(error){ console.log("Request callback failed"); }) </script> </body> </html>
Effect:
To understand that these interceptors need to be based on a certain es6 Promise base, this effect occurs because the request was intercepted by the request interceptor before sending the request, and the request interceptor returned an object config that is not a Promise instance, so the next interceptor invokes a successful callback, so the print response interceptor succeeds. The response to the interceptor's successful callback then returns the object response of the non-Promise instance, so the final request callback is the successful callback, so the return request call succeeds.
Try the following again to request the interceptor's successful callback to return Promise in reject state.
Effect:
The above effect occurs because the Promise instance object that returned reject status in the successful callback of the request interceptor is judged to have failed, and then the Promise instance object in reject status is returned in the failed callback when the next callback in the callback chain is called in response to the callback of the interceptor. So a failed callback was called on the callback page of the real request.
The above effect is the same as Promise.
Effect of multiple interceptors: Add a request interceptor and a response interceptor:
You can see request interceptors like stacks, LIFO, response interceptors like queues, FIFO.
You can adjust config in the request interceptor, such as adding a timeout or something, and you can adjust the response return value in the response interceptor, such as when I return to the callback function and only want the response body part.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>axios Interceptor</title> </head> <body> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> //This is the api that sets the request interceptor, passing in two callbacks, the first successful callback and the second failed callback. axios.interceptors.request.use( function(config){ console.log("Request Interceptor 1 call succeeded"); return config; }, function(error){ console.log("Request interceptor 1 call failed"); return Promise.reject(error) } ) axios.interceptors.request.use( function(config){ //Set Request Timeout config.timeout = 5000; console.log("Request Interceptor 2 call succeeded"); return config; }, function(error){ console.log("Request interceptor 2 call failed"); return Promise.reject(error) } ) //This is the api to set the response interceptor, the first successful callback and the second failed callback axios.interceptors.response.use( function(response){ console.log("Response Interceptor 1 call succeeded"); console.log(response); //When returning to the request callback, as long as the data data data return response.data; }, function(error){ console.log("Response interceptor 1 call failed"); return Promise.reject(error); } ) axios.interceptors.response.use( function(response){ console.log("Response Interceptor 2 call succeeded"); return response; }, function(error){ console.log("Response interceptor 2 call failed"); return Promise.reject(error); } ) axios.get("http://localhost:3000/posts/1") .then(function(response){ // console.log("Request Callback Succeeded"); console.log(response); }).catch(function(error){ console.log("Request callback failed"); }) </script> </body> </html>
Effect:
Cancel Request
Canceling a request means waiting for a period of time for no response after the request has been sent and you can cancel it.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>axios Cancel Request</title> </head> <body> <button id="btn1">Send Request</button> <button id="btn2">Cancel Request</button> <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script> <script> //Step 1: Define a global cancel variable with an initial value of null let cancel = null; document.getElementById("btn1").onclick = function(){ axios.get("http://localhost:3000/posts/1", { //Step 2: Configure the cancelToken property value in the requested configuration object and assign the c parameter of the function to the global variable cancel cancelToken:new axios.CancelToken(function(c){ cancel = c; }) }) .then(function(response){ // console.log(response); }).catch(function(error){ console.log("Request callback failed"); }) } document.getElementById("btn2").onclick = function(){ //Step 3: Calling the cancel function cancels the request reception cancel(); } </script> </body> </html>
The response time of the server needs to be adjusted to 3 seconds, otherwise the request cannot be cancelled if it is too fast.
json-server --watch db.json -d 3000