React请求配置

1. fetch配置

(1) 配置文件@utils/fetch

import { message } from "antd";
import { Cookies } from "react-cookie";

//配置baseURL
fetch.config.baseURL = "https://xxx.com"

//获取cookies实例
const cookies = new Cookies();

//请求拦截器(将本地token携带在请求头中)
fetch.interceptors.request.use(
    (config) => {
        config.headers.token = cookies.get('user_token')
        return config
    }
)

//响应拦截器
fetch.interceptors.response.use(
    async (res) => {
        const { data } = await res.json();
        return data;
    },
    (err) => {
        message.error(err?.errorMsg)
        return new Promise(() => { });
    }
);

export default fetch;

(2) 在组件中应用

import fetch from "@utils/fetch"

const App = () => {

    useEffect(() => {
        fetch('/user').then((data)=>{
            console.log(data);
        })
    },[])

    return <div></div>
}

2. axios配置

(1) 配置文件@utils/request

import axios from "axios";

// 准备授权接口数组,将需要携带token的API接口,放在数组中,请求拦截器就可以根据当前请求是否需要授权,来决定是否在请求头中添加token。
const authAPIs = [];
axios.defaults.baseURL = "https://lianghj.top:8888/api/private/v1/";
// 添加请求拦截器: 默认所有请求在发送之前,都会先经过请求拦截器的拦截,我们可以给请求添加一些通用的配置。
axios.interceptors.request.use(
  function (config) {
    // config.url!.includes config.url?.includes: ?和!也表示断言的意思,表示url属性一定存在值。不可能为undefined.
    // (config.url as string).includes()
    if (authAPIs.some((api) => config.url.includes(api))) {
      const userInfo = localStorage.getItem("userinfo");
      if (userInfo) {
        const { token } = JSON.parse(userInfo);
        config.headers["authori-zation"] = token;
      }
    }
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // 2xx 范围内的状态码都会触发该函数。
  // 对响应数据做点什么
  return response;
}, function (error) {
  // 超出 2xx 范围的状态码都会触发该函数。
  // 对响应错误做点什么
  return Promise.reject(error);
});

export default function request(url, body, method, headers) {
  return new Promise((resolve, rejcet) => {
    axios({
      url,
      method: method ? method : "GET",
      data: body,
      headers,
    }).then(({ data }) => {
      resolve(data);
    });
  });
}

(2) 在组件中应用

import request from "@utils/request";

const App = () => {

    useEffect(() => {
        request('/user').then((data)=>{
            console.log(data);
        })
    },[])

    return <div></div>
}

  • 10
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王布尔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值