One 、 What is? axios ?
axios Is based on Promise Of ajax Packaging Library , It is also the most popular front-end at present ajax Request Library . Simply put, send get、post request , It's a lightweight Library , When in use, you can directly introduce .
Two 、axios Characteristics
- Asynchronous ajax Request Library .
- On the browser side and node End can be used .
- Support Promise API.
- Support request and response interception .
- Automatic conversion of response data JSON data .
- Support request cancellation .
- Multiple requests can be sent in batches .
- The client supports security protection , Free from XSRF attack .
3、 ... and 、axios API
3.1、 install
/* npm install */
npm install axios --save
/* bower install */
bower install axios
/* Use yarn */
yarn add axios
/* cdn introduce */
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Copy code
notes : If a simple static page uses , Suggest cdn Mode introduction .
3.2、axios API
towards axios Transmission related configuration parameters , Create request . Such as :axios(config)
/* If you send a post The requested configuration parameters are as follows */
axios({
method: 'post', // Request method
url: '/user/12345', // Access interface
data: { // To transmit data
firstName: 'Fred',
lastName: 'Flintstone'
}
});
Copy code
/* If you send a get The requested configuration parameters are as follows */
axios({
method: 'get',
url: 'http://localhost:80/one',// Request interface
responseType: 'stream'// Response form
})
.then(function (response) {
response.data.pipe(fs.createWriteStream('save.jpg')) // Save the picture
});
Copy code
3.3、axios Request method
above axios API Every time a request is made , You need to set its request method, response header timeout and other information , It is cumbersome to use , For convenience ,axios Aliases are provided for all supported request methods , The request can be initiated directly in a specified way , Other parameters can be set globally . Such as :
axios('/user/id=1');
Copy code
Above axios Send the request directly , When the request mode is not set , By default get request , And ajax and fetch identical . So it's a get request , You can also use get Method to send , The following example :
axios.get(
'1.txt' ,
{
params:{id:'1'}
}
).then(res=>{
console.log(res);
})
.catch(err=>{
console.log(err);
})
Copy code
It can be written in brief. axios(url,config).
Other specific methods are :
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 code
3.4、 Send requests in bulk
Multiple network requests are often executed concurrently in network requests , Sometimes we need to deal with their returned results in a unified way , therefore axios Concurrent processing .axios.all() Multiple network requests can be sent in parallel , Wait until all requests return , To continue processing .
Use the syntax :
/* The first way to deal with it */
axios.all([
axios.get(URL1),
axios.get(URL2),
]).then(res=>{
console.log(res) // Back to res Is an array ,res[0] Is the first request data res[1] Is the second request data
})
/* The second way to deal with it */
axios.all([
axios.get(URL1),
axios.get(URL2),
]).then(
axios.spread((res1,res2)=>{
res1 // Is the first request to return data
res2 // Is the second request to return data
})
)
Copy code
Use axios.spread Can automatically split request return data .
1.5、 Global default configuration
The global default configuration is mainly used for each request . Save time typing code , When you want to modify , Just change one and you can change it all .
Common global default configurations are :
axios.defaults.baseURL = "http://localhost:8080/" // Configure the domain name
axios.defaults.timeout = 6000; // In milliseconds , Set timeout
/* Head set */
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
Copy code
3.6、axios example
// Configure default parameters when instantiating
const instance = axios.create({
baseURL: 'https://api.example.com'
});
// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN
Copy code
Why axios Instantiation , Because global instantiation http The request has a global response interception , When some of our interfaces cannot return status codes , We will not get response, At this point, we need to be in the current api Re instantiate a axios, Set a new response intercept code .
3.7、 Interceptor
The interceptor is divided into two , There are request interception and response interception , Some businesses can be handled uniformly .
- Request interceptor :
/*
Request interceptor
Uniformly add... Before sending the request token
*/
axios.interceptors.request.use(config=>{
config.headers.token = sessionStorage.getItem("token") // add to toke
return config
},err=>{
console.log(err)// Request error
})
Copy code
- Response interceptors
axios.interceptors.response.use(response=>{
return response
},err=>{
console.log(err)// Response error
})
Copy code
3.8、 Response content
Basically in use , The first instance request succeeded , Print the results console.log(res) . The results are as follows :
{
data:{},
status:200,
// Returned from the server http Status text
statusText:'OK',
// Response header information
headers: {},
//config Some configuration information at the time of request
config: {}
}
Copy code
Four 、axios Common applications
axios It can be used on the browser side , It can also be in node.js Use in . What is sent on the browser side is XMLHttpRequest, stay node.js Send the http . image VUE、React、Node And other projects can use axios.
版权声明
本文为[Front end person_ pleasing]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/09/20210909122358654W.html