在ReactJS中导出实例后如何修改axios实例? [英] How to modify axios instance after exported it in ReactJS?

查看:29
本文介绍了在ReactJS中导出实例后如何修改axios实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用:

axios.defaults.headers.common['Authorization'] = 'Bearer ' + token;

在用户登录应用程序后设置标头,但刷新页面时将删除此配置.

to set header after user make login in application, but when refresh the page this configuration is removed.

我想在用户登录时为来自axios的所有请求设置此配置.

I would like to set this configuration for all requests from axios, when user make login.

我做到了手动设置此配置,将这行代码放在导出axios实例之前.

I got do that setting this configuration manually, putting this line of code before to export axios instance.

现在,我需要在用户进行登录时设置此配置.我该怎么办?

Now, I need to set this configuration when user make login. How can I do that?

推荐答案

您可能想编写一个中间件模块来获取/设置 localStorage 中的令牌并将其应用于您的Axios实例.过去,当我使用Axios时,通常会这样做:

You're probably going to want to write a middleware module to get/set the token in localStorage and apply it to your Axios instance. In the past when I used Axios, I typically did it like this:

import axios from 'axios';
import { API_URL } from '../constants/api';

const API = axios.create({
  baseURL: `${API_URL}`,
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json',
  },
});

API.interceptors.request.use(
  config => {
    const token = sessionStorage.getItem('jwt');

    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    } else {
      delete API.defaults.headers.common.Authorization;
    }
    return config;
  },

  error => Promise.reject(error)
);

export default API;

您将需要创建函数来获取/设置 localStorage 中的JWT,但是如果这样做,这应该对您有用.这将在发出每个请求之前从 localStorage 中获取JWT,因此即使用户刷新了页面,只要用户在 localStorage 中具有有效的JWT,它也不会中断.

You'll need to create functions to get/set the JWT in localStorage, but if you do that, this should work for you. This will fetch the JWT from localStorage before making each request, so it won't break even if the page is refreshed as long as the user has a valid JWT in localStorage.

这篇关于在ReactJS中导出实例后如何修改axios实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆