【问题标题】:How to log user out with Axios using authorization bearer + token如何使用授权承载 + 令牌使用 Axios 注销用户
【发布时间】:2021-10-16 14:10:38
【问题描述】:

我有一个应用程序,我通过连接到后端(使用 axios)并获取存储在 localStorage 中的 JWT 令牌来登录用户。我的问题在于注销功能。我目前这样做:


async endAuth(context) {
    try {
      await axios.post("auth/logout", {
        headers: {
         Authorization:
            "Bearer " + JSON.parse(localStorage.getItem("currentUser")).token,
        },
      });
      localStorage.clear();
      context.commit("setUser", {
        token: null,
        userId: null,
      });
    } catch (e) {
      const error = new Error("Something went wrong");
      throw error;
    }
}

这不起作用。与 API 的连接已建立,但我从后端收到 401 错误 {success: false, message: 'Expired or Invalid Token'}

现在我尝试在标题中添加"Content-Type": "application/json", 仍然没有成功。

我还更改了我的代码以使用 fetch() API 中的 JavaScript 构建。这很有效!代码如下:

async endAuth(context) {
  let url = baseURL + "/auth/logout";
  const response = await fetch(url, {
      method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization:
        "Bearer " + JSON.parse(localStorage.getItem("currentUser")).token,
    },
    });
    const responseData = await response.json();
    if (!response.ok) {
      const error = new Error(
        responseData.message || "Failed to authenticate. Check your login data."
      );
      throw error;
    } else {
      localStorage.clear();
      context.commit("setUser", {
        token: null,
        userId: null,
      });
    }
}

我还尝试通过 axios.defaults.headers.common["Authorization"] = "Bearer " + localStorage.getItem("currentUser").token; 设置 axios 标头 - 不走运 我在 axios 请求中遗漏了什么吗?

【问题讨论】:

  • 您的 API 是否接收到正确的令牌?如果是,问题似乎出在服务器端。
  • 我检查了响应负载,它看起来正确headers: {Content-Type: "application/json",…} Authorization: "Bearer [correctToken]" Content-Type: "application/json"
  • @AyushGupta 更新。我意识到代码确实有效 - 但只有在我刷新页面之后

标签: javascript api axios jwt fetch


【解决方案1】:

一般的简短解决方案:

// previus logout
this.$axios.setHeader('Authorization', `Bearer ${localStorage.getItem("token")}`);
// after logout
this.$axios.setHeader('Authorization', null)
  

具体长解(问题):

 async endAuth(context) {
        try {
          this.$axios.setHeader('Authorization', `Bearer ${JSON.parse(localStorage.getItem("currentUser")).token}`);
          await axios.post("auth/logout");
          localStorage.clear();
          context.commit("setUser", {
            token: null,
            userId: null,
          });
          this.$axios.setHeader('Authorization', null)
        } catch (e) {
          const error = new Error("Something went wrong");
          throw error;
        }
    }

这只是发生在我的nuxt上,希望其他人有用

【讨论】:

    猜你喜欢
    • 2021-08-28
    • 2018-07-04
    • 2019-12-24
    • 2021-04-15
    • 2019-05-21
    • 2019-02-24
    • 2022-10-15
    • 1970-01-01
    • 2020-08-28
    相关资源
    最近更新 更多