Axios interface encapsulation, how comfortable how to
Main.js is introduced for global registration
import https from "./ElementUI/https"; // The axios interface encapsulates vue.prototype.$https= https; // Global register, using this method.$https
Copy the code
HTTP. Js code (reference other bloggers, forget which one the bloggers are, but nuggets have a better one, you can look into juejin.cn/post/684490…)
You can adjust it according to your own needs
import axios from 'axios';
import qs from 'qs'; axios.defaults.timeout = 10000; / / / / response time axios. Defaults. Headers. Post ['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'; // configure the request header //axios.defaults.baseURL ='http://t.weather.sojson.com/api'; / / / / configuration interface address POST preach and serialization (add request interceptor) / / axios. Interceptors. Request. Use ((config) = > {/ / / / / / before sending a request to do somethingif (config.method === 'post') { // config.data = qs.stringify(config.data); / / / /}return config;
// }, (error) => {
// console.log('Incorrect parameter passing') / /returnPromise.reject(error); / /}); / / return status determine response interceptor (add) axios. Interceptors. Response. Use ((res) = > {/ / do something for the response dataif(! res.data.success) {return Promise.resolve(res);
}
return res;
}, (error) => {
console.log('Network exception')
returnPromise.reject(error); }); // Return a Promise(send post request)export function fetchPost(url, params) {
returnnew Promise((resolve, reject) => { axios.post(url, params) .then(response => { resolve(response); }, err => { reject(err); }) .catch((error) => { reject(error); }); }); } return a Promise(send a get request)export function fetchGet(url, param) {
// console.log(url)
return new Promise((resolve, reject) => {
axios.get(url, {
params: param
})
.then(response => {
resolve(response);
}, err => {
reject(err);
})
.catch((error) => {
reject(error);
});
});
}
export default {
fetchPost,
fetchGet,
};
Copy the code
Page reference
Star sea, forge ahead!