Easy encapsulation of AXIos requests
NPM install axios –save
2. Create http.js in/SRC /static/
/** * Created by Administrator. */ import axios from 'axios'; // Set the request timeout time axios.defaults.timeout = 5000; // Set the domain name prefix axios.defaults.baseURL = "; / / HTTP request interceptor axios. Interceptors. Request. Use (config = > {/ / const token = getCookie (' name '); config.data = JSON.stringify(config.data); Config. headers = {' content-type ': 'application/x-www-form-urlencoded'}; // if(token){ // config.params = {'token':token} // } return config; }, error => { return Promise.reject(err); }); / / HTTP response interceptor axios. Interceptors. Response. Use (response = > {the if (response) data) errCode = = 2) {router. Push ({path: "/ login", querry: {redirect: router. CurrentRoute. FullPath} / / from which page jump})} return response; }, error => { return Promise.reject(error) } ); @param url @param data @returns {Promise} */ export function get(url, params = {}) { return new Promise((resolve, reject) => { axios.get(url, { params: params }) .then(response => { resolve(response.data); }). Catch (err => {reject(err)})} /** * Encapsulates POST requests * @param URL * @param data * @returns {Promise} */ export function post(url, data = {}) { return new Promise((resolve, reject) => { axios.post(url, data) .then(response => { resolve(response.data); }, err => { reject(err) }) }) }Copy the code
3. Import in main.js
$prototype.$post=post; Vue.prototype.$get=get;Copy the code
Secondary encapsulation of AXIOS for plug-in use
NPM install axios –save
2. In the SRC folder, create the HTTP folder and create the following files:
Api.js: The default configuration for secondary encapsulation of AXIOS
Config. js: axios default configuration
Index.js: Encapsulates AXIos as a plug-in
Interface-.js: Defines the request interface file
1) config.js: axios default configuration
Export default {method: 'post', // baseURL: '', // headers: {' content-type ':'application/json; Charset = utF-8 '}, // data: {}, // set timeout: 10000, // withCredentials: false, // responseType: 'json' }Copy the code
2) Api.js: Rewraps axiOS’s default configuration
/** * Created by Administrator. */ import axios from 'axios' // import config from './config' // import qs by default From 'qs' // serialize request data Export default function $axios (options) {return new Promise((resolve, resolve, reject) => { const instance = axios.create({ baseURL: config.baseURL, headers: {}, transformResponse: [function (data) {}] } ); / / request interceptor instance. Interceptors. Request. Use (config = > {/ / Tip: 1 / / at the beginning of the request can be combined with open full-screen vuex loading animation / / Tip: 2 // Take the token, // config.headers[' x-token '] = getToken() // //} else {// // redirects to the login page //} // Tip: 3 // According to the request method, serialize the passed parameters, According to the requirements of the back-end whether to serialize the if (config) method) toLocaleLowerCase () = = = 'post' | | config. The method. The toLocaleLowerCase () = = = 'put' | | config.method.toLocaleLowerCase() === 'delete') { config.data = qs.stringify(config.data) } return config; }, error => {// do something when requesting an error (interface error, timeout, etc.) // Tip: 4 // close loAdding console.log('request:', error); If (error.code === 'ECONNABORTED' && error.message.indexof ('timeout')! // return service.request(originalRequest); // Return service.request(originalRequest); } // 2. Redirects to error page const errorInfo = error.response console.log(errorInfo) if (errorInfo) {// error Reject const errorStatus = errorinfo. status; // If the error is a catch, see the Promise. // 404 403 500... Router.push ({path: '/error/${errorStatus}'})} return promise.reject (error) // On the other side of the call you can get the error message you want to return}); / / response interceptor instance. Interceptors. Response. Use (response = > {let data; // Response. data is undefined, So you need to use the response. The request. The responseText (string) after Stringify if (response) data = = undefined) {data = response. The request. The responseText } else{data = response.data} switch (data.code) {case ": break; default: } // If the code is not returned correctly, and the login is complete, // Const err = new Error(data.description) // err.data = data // err.response = response // throw err Return data; }, err => {if (err && err.response) {switch (err.response.status) {case 400: err.message = 'request error '; break; Case 401: err. Message = 'Unauthorized, please log in '; break; Case 403: err.message = 'Access denied '; break; Case 404: err.message = 'Request address error: ${err.response.config.url}'; break; Case 408: err.message = 'Request timed out '; break; Case 500: err.message = 'Server internal error '; break; Case 501: err.message = 'Service not implemented '; break; Case 502: err.message = 'Gateway error '; break; Case 503: err.message = 'Service unavailable '; break; Case 504: err. Message = 'Gateway timed out '; break; Case 505: err.message = 'HTTP version is not supported '; break; default: } } console.error(err); // message. error(' error: ${err} '); return Promise.reject(err); // Return error message returned by interface}); // Request processing instance(options). Then ((res) => {resolve(res); return false }) .catch((error) => { reject(error); })})}Copy the code
3) interface-.js: defines the request interface file
/** * Created by Administrator. */ // import API import axios from './ API '/* Create all interfaces together for easy maintenance * If the project is large, you can create urls as separate files, Export const query = params => {return axios({url: '/news/index', method: 'post', params }) }; export const mock = data => { return axios({ url: '/mock', method: 'get', data }) }; // Export default {query, mock} as neededCopy the code
4) index.js: Wrap AXIos as a plug-in
/** * Created by Administrator. */ / import apiList from './interface' const install = Vue => {if (install.installed) return; install.installed = true; Object.defineproperties (vue.prototype, {get() {return apiList}})}; export default installCopy the code
5) Introduce index in main.js
Import HTTP from './ HTTP /index' vue. use(HTTP)Copy the code
6) Make a call in the component
<template> <div > < p@click ="getMsg"> </p> </div> </template> <script> methods: { getMsg(){ this.$api.query().then(res=>{ console.log(JSON.parse(res)); }).catch(err=>{ alert(err); }); } } } </script>Copy the code