如何使用授权承载+令牌使用Axios注销用户

zazmityj  于 2023-08-04  发布在  iOS
关注(0)|答案(1)|浏览(116)

我有一个应用程序,我通过连接到后端(使用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的连接已建立,但我从{success: false, message: 'Expired or Invalid Token'}后端收到401错误
现在我尝试添加"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请求中错过了什么吗?

gcuhipw9

gcuhipw91#

一般短解:

// 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,我希望别人是有用的

相关问题