axios请求接口封装
配置页:
import axios from "axios"; import mconfig from "./config" import {Message} from "element-ui" import router from "../router" axios.defaults.baseURL = mconfig.hosts; axios.defaults.headers["Content-Type"] = "application/json"; axios.interceptors.request.use( function(config) { let token = JSON.parse(sessionStorage.getItem("token")); token && (config.headers.cnm = token); return config; }, function(err) { //console.error(err); } ); axios.interceptors.response.use(function(res){ if(res.status==200){ switch(res.data.code){ case 200: return res; break; case 300: Message({ type:"error", message:res.data.message?res.data.message:res.data.msg }) break; case 500: Message({ type:"error", message:res.data.message?res.data.message:res.data.msg }) break; case 400: Message({ type:"error", message:"请完整填写表单" }) break; case 401: Message({ type:"error", message:res.data.message?res.data.message:res.data.msg }) sessionStorage.removeItem("token"); sessionStorage.removeItem("store"); router.push("/login") break; case 403: Message({ type:"error", message:res.data.message?res.data.message:res.data.msg }) break; case 406: Message({ type:"error", message:res.data.message?res.data.message:res.data.msg }) break; } return Promise.reject(res) }else { } return res },error=>{ Message({ type:"error", message:"网络出现波动,请稍后重试" }) return Promise.reject(error) }) export default axios;
封装:
import promise from 'es6-promise' promise.polyfill() import "core-js/stable"; import "regenerator-runtime/runtime"; import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' import './routerConfig' import "@/assets/css/global.css" import './plugins/element.js' import 'element-ui/lib/theme-chalk/index.css' import axios from '@/utils/axiosConfig.js' // import CookieJs from '@/utils/Cookie.js' import mconfig from "@/utils/config.js" Vue.prototype.$http = axios Vue.prototype.mconfig=mconfig Vue.config.productionTip = false new Vue({ router, store, created() { // 通过sessionStorage进行状态保存 sessionStorage.getItem('originStore') || sessionStorage.setItem('originStore', JSON.stringify(this.$store.state)) sessionStorage.getItem('store') && this.$store.replaceState(Object.assign({}, this.$store.state, JSON.parse(sessionStorage.getItem('store')))); window.addEventListener('beforeunload', () => { sessionStorage.setItem('store', JSON.stringify(this.$store.state)) }); }, mounted() { // CookieJs.generateCookie() }, render: function (h) { return h(App) } }).$mount('#app')