After Vue was updated to 2.0, the author declared that instead of updating vue-resource, he would recommend axios and update vue-resource to axios in the project, which proved to be a good HTTP client. It simplifies and encapsulates HTTP-related operations as much as possible and is very convenient to use in Web App.
To use axios, of course, install the installation command as follows (of course, if you introduce it through script)
//Installation method
npm install axios
//Introducing axios
import axios from 'axios';
//Add to Vue Global
Vue.prototype.$http = axios;
axios provides the following requests
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
Here config is the basic information configuration for requests, such as request headers, etc. Here we can reduce a lot of extra processing code and use it more gracefully and directly.
//config
import Qs from 'qs'
{
//The interface of the request, such as axios.get(url,config) when requested; the URL here overrides the URL in config
url: '/user',
// Request method is the same as above.
method: 'get', // default
// Basic url prefix
baseURL: 'https://some-domain.com/api/',
transformRequest: [function (data) {
// Here you can process the request data before sending the request, such as form-data formatting, etc. Here you can use the Qs introduced at the beginning (this module was installed when axios was installed, no additional installation is required).
data = Qs.stringify({});
return data;
}],
transformResponse: [function (data) {
// Here, the returned data is preprocessed
return data;
}],
// Request header information
headers: {'X-Requested-With': 'XMLHttpRequest'},
//Parameter parameter
params: {
ID: 12345
},
//The post parameter, using axios.post(url,{},config); if there is no additional, an empty object must be used, otherwise an error will be reported.
data: {
firstName: 'Fred'
},
//Set timeout time
timeout: 1000,
//Return data type
responseType: 'json', // default
}
At the same time, Axios provides us the processing method when multiple requests are initiated (axios request returns a promise, tracking errors only need to add a catch at the end. )
this.$http.all([
this.$http.get(this.allport.goodDetails, {
params: {
goodsId: this.goodsId
}
}),
this.$http.get(this.allport.recommend, {
params: {
id: this.goodsId
}
})
])
.then(this.$http.spread((goodRes, recommendRes) => {
console.log(goodRes);
console.log(recommendRes);
}))
.catch((error) => {
console.log(error);
});
Of course, you can also set the overall situation.
axios.defaults.baseURL = 'https://xxxx';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//Of course, you can also configure it this way.
var instance = axios.create({
baseURL: 'https://api.example.com'
});
And axios interceptor setting request header with vuex
axios.interceptors.request.use(function (config) {
let basicstr = store.state.accessToken;
config.headers.Authorization = `Bearer ${basicstr}`;
return config;
}, function (error) {
return Promise.reject(error);
});
Of course, when using axios'post request, the Content-Type attribute in his request header is application/json;charset=UTF-8. This leads to the incorrect format of the parameter data we transmit and the incorrect parameters can not be obtained in the background. (as shown)
Someone wants to ask if it's OK to change the Content-Type, but unfortunately not. This seems to be a bug in axios. Someone mentioned the issue, but it still hasn't been solved. After searching for information on the Internet, he found a solution and used URLSearchParams to process parameters. However, the compatibility of URLSearchParams is not high, so it makes the URLSearchParams compatible. More attention should be paid when using it, as shown in the following examples
let param = new URLSearchParams();
param.append('username', userName);
this.$http.post(_this.allport.userLogin, param)
.then(function (response) {
response = response.data;
console.log(response);
}).catch(function (error) {
console.log(error);
});
This is the use of axios in the project.