What is the method for encapsulating and using axios?
The methods for packaging and using axios are as follows:
- Install axios: Run the following command in your terminal to install the axios library.
npm install axios
- To introduce axios: In the file where you need to use it, import axios with the following code.
import axios from 'axios';
- receive
axios.get('/api/mydata')
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
- publish
axios.post('/api/mydata', { name: 'John', age: 30 })
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
- default headers
axios.defaults.headers.common['Authorization'] = 'Bearer TOKEN';
- request interceptors
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
- response interceptors
axios.interceptors.response.use(function (response) {
// 对响应数据做些什么
return response;
}, function (error) {
// 对响应错误做些什么
return Promise.reject(error);
});
These are the basic methods for packaging and using axios, which can be further configured and utilized as needed.