【问题标题】:How to use axios interceptors in ES6 generators?如何在 ES6 生成器中使用 axios 拦截器?
【发布时间】:2021-04-18 16:33:05
【问题描述】:

目前,我有这个 Axios 调用,我想要实现的是在 ES6 生成器中使用拦截器。

如果后端服务发回“401”响应,我想使用 axios 拦截器重试请求,有什么建议吗?

const token = '...';

export function* getUsers(user) {
  return yield axios({
    headers: {
      Accept: "Aplication/json",
      Authorization: `Bearer ${token}`,
    },
    method: "get",
    url: '/getUsers/:id'
 })
  .then(data => data)
  .catch(e => e)
 }

【问题讨论】:

  • 你必须使用yeild吗?
  • 是的@nicholasnet,因为我正在使用 redux-saga

标签: javascript reactjs ecmascript-6 axios redux-saga


【解决方案1】:

也许你可以试试这样的。

import axios from "axios";

export const getClient = (token) => {
    const options = {};
    if (token !== null) {
        options.headers = { Authorization: `Bearer ${token}` };
    }

    const instance = axios.create(options);
    instance.interceptors.response.use((response) => response, (error) => {
        if (error.response.status === 401) {
            window.location = '/logout'; // Or whatever you want to do
        }
    
        return Promise.reject(error);
    });
    
    return instance;
};

export function* getUsers(user) {

    return yield getClient('JTW_TOKEN').get('/getUsers/:id').then(data => data).catch(e => e)
}

我个人更喜欢为 get/post/delete/put/patch 等设置单独的方法,但无论如何都不是必须的。

【讨论】:

    猜你喜欢
    • 2019-03-15
    • 2020-09-28
    • 2019-06-26
    • 2022-06-21
    • 2018-11-01
    • 2020-09-27
    • 2019-04-28
    • 2023-01-10
    • 2023-01-21
    相关资源
    最近更新 更多