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



我有一个应用程序,我通过连接到后端(使用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",添加到标题中仍然没有运气。

我也改变了我的代码使用JavaScript构建在fetch()API。这是有效的!下面是代码:

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的请求我是不是漏掉了什么?

一般简写:

// 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;
}
}

这是刚刚发生在我与next,我希望别人是有用的

最新更新