【问题标题】:Axios request interceptor not working on browser refreshAxios 请求拦截器在浏览器刷新时不起作用
【发布时间】:2019-11-27 04:02:30
【问题描述】:

我在我的反应应用程序中使用 axios 拦截器来传递每个请求的令牌。 我在登录后最初调用 setupAxiosInterceptors 方法(参见下面的代码)。在我刷新浏览器之前,这一切正常。

    const registerSucessfulLoginForJwt = (username, token) => {
          sessionStorage.setItem(USER_NAME_SESSION_ATTRIBUTE_NAME, username)
          setupAxiosInterceptors(createJwtAuth(token))    //Calling the axios interceptor at the time of login
    }

见下文 setupAxiosInterceptors 方法

const setupAxiosInterceptors = (token) => {
   Axios.interceptors.request.use((config) => {
     if(isUserLoggedIn()) {
        config.headers.authorization = token
        sessionStorage.setItem('authorization', token)
     }
    return config
  })
 }

有没有想过如何解决这个问题以使其始终有效?

【问题讨论】:

    标签: reactjs axios


    【解决方案1】:

    我能够找到解决问题的方法。我创建了一个 ApiSetup.js 文件,在该文件中创建了一个可用于所有请求的自定义 axios 实例。

        const request = axios.create({
            baseURL: API_PATH_BASE
        })
    
        request.interceptors.request.use(config => {
            const currentUser = AuthenticationService.getLoggedInUser() //You can get the user directly from the cookie or session storage...
            if(currentUser.userName) {
                config.headers.Authorization = currentUser.userToken
            }
        return config
        }, err => {
           console.log(err)
        return Promise.reject(err)
        })
    
        export default request
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-13
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      • 2018-08-23
      • 2020-09-25
      • 2021-01-23
      • 2023-02-08
      相关资源
      最近更新 更多