LocalStorage 中的令牌存在,但没有放入我的 Axios 实例中

mas*_*er6 2 local-storage reactjs

我的组件之一未加载,因为本地存储中的令牌未在我的 Axios 请求中发送。

\n

这是流程。我有一个Login组件,一旦用户经过身份验证,它就会在本地存储中设置令牌。这是该函数:

\n
   AuthService.authenticateEmployee(employee).then((r) => {\n      if (r != null && r.data.jwt != null) {\n        localStorage.setItem("token", r.data.jwt);\n        console.log(r.data.jwt);\n        console.log("nav to tickets now");\n        this.props.history.push("/tickets");\n      }\n    });\n  };\n
Run Code Online (Sandbox Code Playgroud)\n

然后它会带您到/tickets我的问题所在。尝试TicketsComponent\n验证令牌。如果无效,则应将用户重定向回登录页面。

\n
   AuthService.validateToken()\n      .then((res) => {\n        console.log("step 1");\n        if (res == undefined || res == null || !token) {\n          this.props.history.push("/login");\n        }\n      })\n      .then(() => {\n        console.log("step 2");\n\n        TicketService.getTickets().then((res) => {\n          if (this._isMounted) {\n            this.setState({ tickets: res.data });\n          }\n        });\n      });\n
Run Code Online (Sandbox Code Playgroud)\n

这是validateToken()

\n
  validateToken() {\n    console.log(" about to try validating");\n    return AxiosInstance.get("authenticate")\n      .then("did it")\n      .catch((err) => console.log(err));\n  }\n
Run Code Online (Sandbox Code Playgroud)\n

最后,这就是我指出问题的地方:

\n
const AxiosInstance = axios.create({\n  baseURL: API_BASE_URL,\n  headers: { Authorization: `Bearer ${getTokenFromLocalStorage()}` },\n});\n\nfunction getTokenFromLocalStorage() {\n  const token = localStorage.getItem("token");\n  console.log("the token from local storage is -> " + token);\n  if (token === null) {\n    return undefined;\n  }\n  return token;\n}\n\nexport default AxiosInstance;\n
Run Code Online (Sandbox Code Playgroud)\n

如果我对授权标头的值进行硬编码以使其具有与 LocalStorage 中相同的令牌,那么它就可以工作。但当我尝试使用该getTokenFromLocalStorage功能时却没有。该函数似乎甚至没有被调用。根本console.log()没有被打印。到底是怎么回事?如何将我的令牌正确嵌入到此请求中?

\n

编辑:我在开发人员工具中仔细检查了我的 LocalStorage 。在点击登录按钮之前它是空的。当我单击“登录”时,令牌将按如下所示进行填充:\n localStorage \n但是,它仍然无法让我登录。\n错误

\n

重要提示:所以看来 mygetTokenFromLocalStorage仅在创建 Axios 实例时才会被调用,而不是每次使用它\xe2\x80\x99s 时被调用。如何解决这个问题,以便每次使用 AxiosInstance 时都会调用该函数?

\n

更新:我发现肯定不会从中检索令牌,getTokenFromLocalStorage因为这是请求中发送的标头:\n请求标头

\n

但是,我可以在单击登录并在标题中设置令牌后localStorage.getItem("token")从内部调用,它会显示正确的令牌。TicketsComponent我发布了一张图片,显示单击登录后在 LocalStorage 中设置了令牌,那么发生了什么?

\n

更新#2:我找到了这个 StackOverflow 答案,但它对我来说没有用。有人有主意吗?关联

\n

mas*_*er6 5

我想到了。解决方案是使用拦截器,它是 Axios 实例的一部分。使用拦截器允许您动态设置每个请求的标头,因为它可以随时更改。

const AxiosInstance = axios.create({
  baseURL: API_BASE_URL,
});

AxiosInstance.interceptors.request.use(function (config) {
  // Do something before request is sent
  let token = localStorage.getItem("token");
  config.headers["Authorization"] = "Bearer " + token;
  return config;
});

export default AxiosInstance;
Run Code Online (Sandbox Code Playgroud)

然后它就起作用了。