Install axios

Their search on the nuggets, installation steps do not write, write point to step on the pit key.

Create http.js to encapsulate HTTP POST GET requests

import axios from 'axios'; // import QS from axios'qs'; // Introduce a front-end vant component, which can reference {Toast} from as needed'vant'; // Vant's toast prompt box component // Introduces store import store from'.. /plus/store'; // Import router import router from'.. /plus/router';
Copy the code

The request address varies depending on the development environment

// Environment switch request address changeif (process.env.NODE_ENV == 'development') {/ / development environment / / local cross-domain test / / in vue. Config. Js defined proxy / / see/portal (https://juejin.cn/post/6844904186182631432) axios.defaults.baseURL ='/apis';
}else if (process.env.NODE_ENV == 'debug') {// Debug the environment axios.defaults.baseurl ='bug.ungang.cn';
}else if (process.env.NODE_ENV == 'production') {// Production environment axios.defaults.baseurl ='https://work.ungang.cn';
}

Copy the code

Setting of the POST request header

/ / post request head set axios. Defaults. Headers. Post ['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';

Copy the code

Request interceptor

/ / request interceptor axios. Interceptors. Request. Use (config = > {/ / whether there is in every time before sending a request to judge vuex token / / if it exists, is unified in the HTTP request header and token, Const token = store.state.token; const token = store.state.token; token && (config.headers.Authorization = token);return config;
	},
	error => {
		console.log(error);
		Promise.reject(error);
});
Copy the code

Response interceptor

Axios. Interceptors. Response. Use (response = > {/ / if the returned a status code of 200, shows that interface request is successful, can be normal to get the data / / otherwise throw an errorif (response.status === 200) {
			return Promise.resolve(response);
		} else {
			returnPromise.reject(response); }}, // server status code does not start with 2 error => {if(error.response.status) {switch (error.response.status) {// 401: not logged incase401: // Clear the tokenlocalStorage.removeItem('token');
					store.commit('set_token', null); // The fullPath page will be uploaded. After login, go to the required page store.com MIT ('set_login_after_path', the router. CurrentRoute. FullPath) / / login function goLogin ();break; // 403 Token expiration // The login expiration prompts the user. // Clear the local token and the token object in the VUEX. // The login page is displayedcase403: // Clear the tokenlocalStorage.removeItem('token');
					store.commit('set_token', null); // The fullPath page will be uploaded. After login, go to the required page store.com MIT ('set_login_after_path', the router. CurrentRoute. FullPath) / / jump to the login page goLogin ();break; / / other errors, directly thrown error default: Toast ({message: error. The response. The data message, duration: 1500, forbidClick:true
					});
			}
			returnPromise.reject(error.response); }});Copy the code

Request method function

The get method

/** * get method, corresponding to get request * @param {String} url [request URL] * @param {Object} params [request parameters] */export function get(url, params){
	return new Promise((resolve, reject) =>{
		axios.get(url, {
			params: params
		}).then(res => {
			res = res.data;
			if(res.errcode == 0){
				resolve(res.data);
			}else{
				reject(res);
			}
		}).catch(err =>{
			Toast({
				message: err,
				duration: 1000,
				forbidClick: true}); })}); }Copy the code

Post method

/** * Post request * @param {String} url [requested URL] * @param {Object} params [requested parameters] */export function post(url, params) {
	return new Promise((resolve, reject) => {
		axios.post(url, QS.stringify(params))
		.then(res => {
			res = res.data;
			if(res.errcode == 0){
				resolve(res.data);
			}else{
				reject(res);
			}
		})
		.catch(err =>{
			Toast({
				message: err,
				duration: 1000,
				forbidClick: true}); })}); }Copy the code

Method of use

import { get,post } from './http';
Copy the code