vue中axios 配置请求拦截功能 及请求方式如何封装

main.js 中:

import axios from '................/axios'

axios.js 中:

//axios.js
import Vue from 'vue'
import axios from 'axios'
Vue.prototype.$http = axios

//http request 封装请求头拦截器
axios.interceptors.request.use(config => {
  // console.log("request")
  // console.log(config)

  //请求方式
  let method = config.method.toLowerCase();
  if (method === 'get' || method === 'delete') {
    Object.assign(config.params, {
      "test": "testVAl"
    });
  }
  return config;
}, error => {
  return Promise.reject(err);
});

//http response 封装后台返回拦截器
axios.interceptors.response.use(response => {
  // console.log(response)
//当返回信息为未登录或者登录失效的时候重定向为登录页面
  //   if (response.data.code == 'W_100004' || response.data.message == '用户未登录或登录超时,请登录!') {
  //     router.push({
  //       path: "/",
  //       querry: {
  //         redirect: router.currentRoute.fullPath
  //       } //从哪个页面跳转
  //     })
  //   }
  if (typeof response.data === 'string') {
    return JSON.parse(response.data);
  } else {
    return response;
  }
}, error => {
  return Promise.reject(error)
});

使用:

this.$http.get('/api/......', {params:{}}).then(res => {
                console.log(res)
            }, res => {
                // error callback
            });

猜你喜欢

转载自www.cnblogs.com/xiangsj/p/9030623.html