umi-request 一个新的请求工具

简单封装

import { extend } from "umi-request";
const request = extend({
  prefix: "xxx",//相当于baseurl 
  timeout: 10000,
  errorHandler,
});

function errorHandler(error) {
  const codeMap = {
    500: "系统异常",
    404: "请求无效",
    403: "请求403",
  };
  if (error.response) {
    let status = codeMap[error.response.status];
    if (status) {
      alert(status);
    } else {
      throw error;
    }
  } else {
    throw error;
  }
  //
}

// request拦截器, 改变url 或 options.
request.interceptors.request.use((url, options) => {
  return {
    url,
    options: { ...options, interceptors: true },
  };
});

// 局部拦截器使用
request.interceptors.response.use((response, options) => {
  return response;
});

export default request;

// 使用
 import request from 'xxxx'
  request("/api/getMenu")
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    });


posted @ 2020-12-11 14:48  阿臻  阅读(5009)  评论(0编辑  收藏  举报