How to modify axios instance after exported it in ReactJS?

柔情痞子 提交于 2020-06-17 15:14:42

问题


I am using:

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.

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

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?


回答1:


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;

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.



来源:https://stackoverflow.com/questions/58126608/how-to-modify-axios-instance-after-exported-it-in-reactjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!