axios全局代理实战

栏目: jQuery · 发布时间: 6年前

内容简介:在项目中,为了方便使用,对假设后端api的前缀地址是:那么通用配置信息如下:

在项目中,为了方便使用,对 axios 进行了二次封装,原因如下:

  1. 由于内网服务器的安全策略,put、delete等方法的请求无法发送到后台
  2. 为了方便快速对接后端服务器,api接口的前缀、安全策略过期时间等通用配置应该抽离

公共配置抽离

假设后端api的前缀地址是: //1.1.1.1/api/ ,安全过期时间是5000ms。

那么通用配置信息如下:

const CONFIG = {
    baseURL: '//1.1.1.1/api/',
    timeout: 5000,
};

// ...

const instance = axios.create({ CONFIG });

// ... 

export default instance;

编写拦截器

“拦截器”的做法来源于 设计模式 中的“装饰器模式”,它能在不改变原有函数逻辑的情况下,添加其他业务逻辑。

低耦合的设计非常适用于参数过滤、中间层拦截等场景。

请求拦截器

考虑到业务场景,请求到后端的数据需要在Headers中带有认证数据。

同时,由于不支持put、patch、delete方法,只能在headers中通过添加字段来标识。

const handleRequest = (config) => {
  config.headers.common['Authorization'] = token.get() || '';

  const method = config.method.toUpperCase();
  switch(method) {
    case 'PUT':
    case 'PATCH':
    case 'DELETE':
      //方法转换
      config.headers.common['X-Http-Method-Override'] = method;
      config.method = 'POST';
      break;
    default:
      break;
  }

  return config;
};

instance.interceptors.request.use(handleRequest, error => Promise.reject(error));

返回拦截器

当数据从后端返回,出现错误的时候,也做一层数据过滤拦截。

const hanldeResponseError = (error) => {
  const { response = {} } = error;
  switch(response.status) {
    case 401: // 401:用户未登录需要先登录
      console.log('Unauthorized');
      break;
    case 403:
      console.log('Forbidden');
      break;
    case 400: //操作失败
    case 422: //表单验证失败
      console.log(`Error: ${response.data.message}`);
      break;
    case 404:
    default:
      break;
  }
  return Promise.reject(error);
};

instance.interceptors.response.use(response => response, hanldeResponseError);

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

PHP for the World Wide Web, Second Edition (Visual QuickStart Gu

PHP for the World Wide Web, Second Edition (Visual QuickStart Gu

Larry Ullman / Peachpit Press / 2004-02-02 / USD 29.99

So you know HTML, even JavaScript, but the idea of learning an actual programming language like PHP terrifies you? Well, stop quaking and get going with this easy task-based guide! Aimed at beginning ......一起来看看 《PHP for the World Wide Web, Second Edition (Visual QuickStart Gu》 这本书的介绍吧!

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具