1, the project path, introducing axios, qs dependent
npm install axios
npm install qs
2, a new project in a path commJs src folder, and request.js aps.js new folder in commJs, api.js an interface for writing, written on the package of axios in request.js
request.js
Axios from Import 'Axios' ; Import from the QS 'QS' ; // automatically switched environment axios.defaults.baseURL = process.env._BASEURL // set timeout axios.defaults.timeout = 10000 ; // POST request header axios. defaults.headers.post [ 'the Type-the Content'] = 'file application / JSON; charset = UTF-. 8' axios.defaults.withcredentials = to true // request interceptor (the request issued prior to a processing request) axios.interceptors.request.use ( (config) => { // if the parameter is a post serialized request before sending the request IF (config.method === 'post' {) config.data = config.data; } return config; }, (error) => { return Promise.reject (error); }); // response blocker (treatment response data) axios.interceptors.response.use ((RES) => { // response data to make a judgment, with the background protocol format unified interface returns the console.log ( '>>>>>>> Response:' , RES); IF (res.data.succ = 'OK'!) { // this is determined according to practical situation return Promise.reject (RES); } return RES; }, (error) => { return Promise.reject (error); }); // package get method function get (URL, the params) { return new Promise((resolve, reject) =>{ axios.get(url, params).then(res =>{ resolve(res.data); }).catch(err =>{ reject(err.data); }) }); } // 封装post方法 function post(url, params){ return new Promise((resolve, reject) =>{ axios.post(url, params).then(res =>{ resolve(res.data); }).catch(err =>{ reject(err.data); }) }); } //对外接口 export function request({method, url, data}){ if(method == 'get'){ return get(url, data); }else if(method == 'post'){ return post(url, data); } } export default { install(Vue) { Vue.prototype.$axios = axios; Vue.prototype.$request = function () { return request; } } }
api.js
{Import
Request
} from './request' // list query interface
Export the getList = const (parmas) => {
return Request ({
URL: 'XXX / XXX / XXX',
Method: 'POST',
Data: parmas
})
}
3, in the specific component calls
//index.vue import { getList } from "../../comm/js/api.js"; export default { methods: { getPage() { var param = { currentUser: '', currentPage: "1", pageSize: "10" }; getList(param).then(res => { if (!res.result.list) { this.list = []; } else { this.list = res.result.list; } }); } }