如何在 Vue 中使用 beforeRouteEnter 通过标头发送授权令牌?

问题描述 投票:0回答:0

我正在尝试在用户尝试访问“/”端点之前发送授权持有者令牌,并且我正在使用 Vue Router 提供的 beforeRouteEnter 导航守卫来执行此操作。在后端的“/”路由中,“Authorization”标头未定义,虽然有几次发送令牌的情况,但我无法确定为什么那几次成功。我控制台记录了标题,并且可以验证标题是否已从前端正确更新。

{
    path: "/",
    name: "home",
    component: HomeView,
    beforeRouteEnter: async (to, from, next) => {
      const auth = getAuth();
      auth.onAuthStateChanged((user) => {
        if (user) {
          api.defaults.headers.common["Authorization"] = user.accessToken;
          console.log(api.defaults.headers.common["Authorization"])
          next();
        } else {
          next({ name: "login" });
        }
      });
    },
  },
vue.js router
© www.soinside.com 2019 - 2024. All rights reserved.