Axios profile
Axios is a Promise-based HTTP library that can be used in browsers and Node.js. In today’s front-end development, whether Vue framework or React framework, Axios is the most commonly used Ajax request technology, so mastering the use of Axios is a necessary basic skill for front-end development.
Json – server profile
Before I get into using Axios, I’ll introduce you to a nice library that simulates requests, jSON-Server. When we actually develop projects at work, the normal development process is to define the relevant interfaces at the front and back ends first, and then start the development work at the front and back ends respectively after the definition is completed. So the problem comes, the front-end in the process of development, may need to request interface data, at this time, the back-end development has not been completed, can not provide interface, at this time, what should the front-end do? Of course there are many ways. For example, the front end writes JSON files and uses mock data. Here I will introduce a method to simulate the return of the back end interface: JSON-server.
Usage of json-server
The installation
NPM install -g json-server NPM install -g json-server
Simulate JSON file
Create a new JSON file, such as db.json, in the folder where you want to place the JSON service. Add the desired JSON data to the file, such as:
{
"posts": [{"id": 1."title": "json-server"."auther": "zhangsan"
},
{
"id": 2."title": "json-server"."auther": "zhangsan"}]."comment": [{"id": 1."body": "some comment"."postId": 1
},
{
"id": 2."body": "some comment2"."postId": 2}]."profile": {
"name": "typecode"}}Copy the code
Open the current json file with VScode, open the VScode terminal, go to the current JSON file (db.json directory), execute json-server db.json (where db.json is your new JSON file), and then we should see the following result: We see this smiley face Hi! It means that the service has been successfully started. (It’s as simple as that. Mom no longer has to worry about the back end not serving me.)
We can then preview the data returned by our service using the link in Resources below. The page opens like this:
Ha ha ha, here our service is good, happy.
Axios use
Axios installation
- Use NPM:
$ npm install axios
Copy the code
- Use the CDN:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Copy the code
Tip: If you’re feeling a bit slow, try a domestic resource: go to bootcDN and search for Axios.
Basic use of Axios
Here we introduce CDN in the form of HTML page: the code is as follows:
<head>
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script><meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, < frame style="background:# FFF "> Get </ frame > < frame style=" frame :# FFF" Style ="background:#f00"> Send post</button> <button style="background:#0f0"> Send put</button> <button </button> </div> </body>Copy the code
// part1
let btns = document.querySelectorAll('button');
// Set the default request address beginning
axios.defaults.baseURL = 'http://localhost:3000';
// Set the default request mode
axios.defaults.method = 'GET';
// Set the charming request parameters
axios.defaults.params = {sourceId:1000}
// Set the default request timeout time to send the request again
axios.defaults.timeout = 3000
/ / GET request
btns[0].onclick = function(){
axios({
// Request type
method:'GET'.// URL
url:'/comment'
}).then((response) = > {
console.log(response)
})
}
// Post requests to add data. Data can be added via data. You can see that after the execution, the requested JSON file has more data we added
btns[1].onclick = function(){
axios({
// Request type
method:'POST'.// URL
url: 'http://localhost:3000/posts'.data: {
title:'New culture'.author:'hu shi'
}
}).then((response) = > {
console.log(response)
})
}
// PUT requests to modify some data
btns[2].onclick = function(){
axios({
// Request type
method:'PUT'.// URL
url: 'http://localhost:3000/posts/3'.data: {
title:'New culture'.author:'Cathy'
}
}).then((response) = > {
console.log(response)
})
}
// DELETE Deletes a certain data
btns[3].onclick = function(){
axios({
// Request type
method:'DELETE'.// URL
url: 'http://localhost:3000/posts/3',
}).then((response) = > {
console.log(response)
})
}
Copy the code
Axios creates instance use
Example: If we have two types of requests and the REQUEST URL starts differently, we cannot do this with axios.defaults.baseURL. We can create an instance with Axios as follows:
// part2
// Create an instance
const duanzi = axios.create({
baseURL: 'http://localhost:3000'.timeout:2000
})
duanzi({
url:'/posts'
}).then(response= >{
console.log(response)
})
Copy the code
Axios interceptor
Sometimes, we need to do some processing before Axios request to send, or do some processing, the results of Axios request to return to this time we should have played the interceptor (BGM: changjiang) sample is as follows: through Axios. Interceptors. Request. The request to intercept the use: Here we can add the request’s public parameters via config. Here we see two function parameters, which look familiar to resolve and Reject from Promise. Yes, because Axios is implemented through Promise, These functions are used in the same way as Promise. Through axios. Interceptors. Response. Use to set the response the interceptor, such as the data in the response, we just return results that can return the response. The way of data.
// part3
// Request interceptor
axios.interceptors.request.use(function(config){
console.log('Request for interceptor successful');
config.params = {sysNum: 123}
return config
// throw 'argument is wrong'
}, function(error){
console.log('Request interceptor failed')
return Promise.reject(error)
})
// Response interceptor
axios.interceptors.response.use(function(response){
console.log('Response interceptor successful')
return response
// Response. Data returns data
},function(error){
console.log('Response interceptor failed')
return Promise.reject(error)
})
axios({
url:'http://localhost:3000/posts'
}).then(response= >{
console.log(response)
}).catch(error= >{
console.log(error)
})
Copy the code
Axios cancel request
The cancelToken attribute in AXIos can be used to cancel an AXIos request. For example, we click a button to trigger the sending of asiOS request. Before the request is successfully responded, we click the button again, then the axios request will start again. At this time, we can cancel the last request as follows: Note that the argument c in cancelToken is a method that ends our current AXIos request. To register a global variable cancel, null is first set, and after the AXIOS request is sent, the parameter in the axios. CancelToken instance (the method that terminates the axiOS request) is assigned to the global variable Cancel. When the last request has not gone to response and the next one starts the AXIos request, we determine whether cancel is null. If it is not null, it means that the last request is in progress and response has not been sent yet. At this point we end the last request and send the current request. After the last successful request, set the variable used to hold the last AXIos request termination function to null so that we can make the next request.
<div>
<button>Send the request</button>
</div>
Copy the code
const btn = document.querySelectorAll('button')
let cancel = null
btn[0].onclick = function() {
if(cancel ! = =null) {
cancel()
}
axios({
method:'GET'.url:'http://localhost:3000/comments'.cancelToken: new axios.CancelToken(function(c){
cancel = c
})
}).then(response= >{
cancel = null}}})Copy the code