axios package (with the get process token is introduced in the Content-Type)

Package axios
import axios from 'axios'  //引入axios
import store from '@/store/index'  //引入store
//此处引入router可做请求时错误信息跳转或login处理问题
import router from '@/router'  //引入router

axios.defaults.baseURL = process.env.baseURL;
axios.defaults.headers['Content-Type'] = 'application/json';

// http request 拦截器
axios.interceptors.request.use(
    config => {
        console.log(config);
        if (store.state.token) { // 判断是否存在token,如果存在的话,则每个http header都加上token
            config.headers.Authorization = store.getters.token  //请求头加上token
        }
        if (config.method == 'get') {
            //axios中get请求会移除Content-Type,此处是绕过判断给get添加header
            config.data = true;
            config.headers['Content-Type'] = 'application/json'
        }
        return config
    },
    err => {
        return Promise.reject(err)
    })

// http response 拦截器
axios.interceptors.response.use(
    response => {
        //拦截响应,做统一处理 
        return response
    },
    //接口错误状态处理,也就是说无响应时的处理
    error => {
        return Promise.reject(error) // 返回接口返回的错误信息
    })
Quote
In the main, js in
//引入axios
import axios from 'axios'
//引入axios.js文件,注意路径
import './service/axios'
//挂载到原型链上
Vue.prototype.$ajax = axios;
transfer
//可在axios.js中做统一的错误处理

//post请求

//不带参
this.$ajax.post('/******').then(res=>{})

//带参
let params={a:1,b:2};
this.$ajax.post('/******',params).then(res=>{})

//get请求

//不带参
this.$ajax.get('/******').then(res=>{})

//带参
let params={a:1,b:2};
this.$ajax.get('/******',{params:params}).then(res=>{})

//es6对象可简写
this.$ajax.get('/******',{params}).then(res=>{})
Standing on the shoulders of our predecessors

Guess you like

Origin www.cnblogs.com/chendada/p/11778395.html