在vue项目中对axios进行封装
1、引入axios,qs模块
import axios from 'axios';import Qs from "qs";import store from "./store";
2、配置环境
if (process.env.NODE_ENV == 'development') {//开发环境 axios.defaults.baseURL = "/v1";} else if (process.env.NODE_ENV == 'debug') {//测试环境 axios.defaults.baseURL = "/visual";} else if (process.env.NODE_ENV == 'production') {//生产环境 axios.defaults.baseURL = '';}
3、设置请求超时时间为10s
axios.defaults.timeout = 1000 * 10;
4、post请求头的设置
axios.defaults.headers['Content-Type'] = "application/json;charset=UTF-8";
5、请求拦截
axios.interceptors.request.use(config => {if (!(config.url.includes('login'))) {config.headers = {'token': sessionStorage.token,// "x-ajax": true,// "content-type":'application/json',}}return config;},error => {return Promise.reject(error);})
6、请求响应
axios.interceptors.response.use(response => {return response},error => {//失败判断if (error.response) {switch (error.response.status) {case 401:if (!error.response.config.url.includes('login')) {sessionStorage.token = null;location.reload()}}}return Promise.reject(error.response.data)})export default axios