axios的配置及拦截器

2021-07-02  本文已影响0人  sun_hl

axios的基本配置和拦截配置
http://www.axios-js.com/zh-cn/docs/

// axios.js文件配置

// 自定义实例默认值
const axiosInstance = axios.create({
    baseURL: 'https://some-domain.com/api/',// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
    timeout: 20000,  // 如果请求花费了超过 `timeout` 的时间,请求将被中断
    withCredentials: true  // 表示跨域请求时是否需要使用凭证
});

// 添加请求拦截器
 axiosInstance.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
 }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
 });

// 添加响应拦截器
 axiosInstance.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 对响应错误做点什么
    return Promise.reject(error);
  });


//  执行post请求
axios.post(url, 请求参数);
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 执行get请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 上面的请求也可以这样做
 axios.get('/user', {
      params: {
          ID: 12345
      }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
// 网络请求配置
const hcaxios = {
  instance: null,
  loading: null,

  // 初始化axios实例
  init: function () {
    if (this.instance) return

    const instance = axios.create()
    instance.defaults.timeout = 20000
    
    // 添加请求拦截器
    instance.interceptors.request.use(config => {
      // const token = store.state.adminUser.token
      const token = sessionStorage.getItem('adminToken')
      config.headers.Authorization = 'Bearer ' + token
      return config
    }, error => {
      return Promise.reject(error)
    })

    // response的拦截器,在此进行错误处理,并返回data.data以方便使用
    instance.interceptors.response.use(response => {
      const data = typeof response.data === 'string' ? JSON.parse(response.data) : response.data
      if (parseInt(data.code) === 401) {
        // 未登录或未授权
        Message({message: data.message, type: 'warning'})
        sessionStorage.removeItem('adminToken')
        sessionStorage.removeItem('adminName')
        router.replace({path: '/login'})
        return Promise.reject(data.message)
      }
      if (data.code === 200) {
        return data.data
      } else {
        return data
      }
    }, function (error) {
      if (error instanceof axios.Cancel) {
        error.isCanceled = true
      } else {
        error.isCanceled = false
        Message({message: '请求异常或超时,请稍后重新尝试!', type: 'warning'})
      }
      return Promise.reject(error)
    })

    this.instance = instance
  },

  get: function (apiName, opts) {
    if (opts && typeof opts === 'object') {
      opts = { params: opts }
    }
    return hcaxios.request(apiName, opts, 'get')
  },

  send: function (apiName, opts) {
    if (opts && typeof opts === 'object') {
      opts = { data: opts }
    }
    return hcaxios.request(apiName, opts, 'post')
  },

  request: function (apiName, opts, method) {
    console.log('call api', apiName)
    this.init()

    if (typeof apiName === 'object') {
      opts = apiName
      apiName = opts.apiName
    } else if (typeof apiName === 'string') {
      if (typeof opts === 'object') {
        opts = { data: opts.data, params: opts.params }
      } else {
        opts = {data: {}, params: {}}
      }
    } else {
      throw new Error('hxaios的参数不正确')
    }
    if (!apiName) {
      throw new Error('apiName is not defined!')
    }

    const {data, params, ...rest} = opts

    return this.instance.request({
      url: apiName,
      method: method,
      data: JSON.stringify(data),
      headers: {'Content-Type': 'application/json', 'charset': 'UTF-8'},
      params,
      ...rest
    })
  }
}

export default {
  get: hcaxios.get,
  send: hcaxios.send
}

vue 使用axios跨域解决方案
2.配置代理

在config文件夹下的index.js文件中的proxyTable字段中,作如下处理:

  dev: {
    env: require('./dev.env'),
    port: 8090,
    autoOpenBrowser: true,
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/api': {
        target:'http://api.douban.com/v2', // 你请求的第三方接口
        changeOrigin:true, // 在本地会创建一个虚拟服务端,然后发送请求的数据,并同时接收请求的数据,这样服务端和服务端进行数据的交互就不会有跨域问题
        pathRewrite:{  // 路径重写,
          '^/api': ''  // 替换target中的请求地址,也就是说以后你在请求http://api.douban.com/v2/XXXXX这个地址的时候直接写成/api即可。
        }
      }
    },
   cssSourceMap: false
  }

3、 js 前端请求头里传 token问题

在前端请求后台的API接口的时候,为了安全性,一般需要再用户登录成功之后才能发送其他请求。因此,在用户登录成功之后,后台会返回一个token给前端,这个时候我们就需要把token暂时保存在本地,每次发送请求的时候需要在header里边带上token(无需再次带上请求名和密码),这个时候本地的token和后台数据库中的token进行一个验证,如果两者一致,则请求成功,否则失败。

sessionStorage.setItem("key","value");    //保存数据到sessionStorage
var data = sessionStorage.getItem("key");   //获取数据
sessionStorage.removeItem("key");                //删除数据
sessionStorage.clear();                                  //删除保存的所有数据
在请求头加上  { headers: { Authorization: `Bearer ${Base.token}` } }
上一篇 下一篇

猜你喜欢

热点阅读