I implemented nuxtserverinit to check whenever there is a cookie with the user's token to load their data. And it works well and the user is authenticated. But when I need to make another request on the pages, an uninformed token error appears, as if I no longer have a header Authorization. And I know it doesn't, because when I set a header on the page, it works normally.
actions.js
export async function nuxtServerInit({ commit, dispatch }, { req, res }) {
if (this.$cookies.get("token")) {
this.$axios.setToken(this.$cookies.get("token"));
await this.$axios
.$get("/user/profile")
.then(response => {
commit("setUser", response.user);
commit("setAuthenticated", true);
commit("setToken", this.$cookies.get("token"));
if (response.user.isAdmin) {
commit("setAdmin", true);
} else {
commit("setAdmin", false);
}
})
.catch(error => {
dispatch("logout");
});
}
}
And later on a page, requests return an uninformed token error. for example:
post.vue
methods: {
async onComment() {
try {
let response = await this.$axios.$post(
"/comment/add",
{
...
}
);
} catch (err) {
{...}
}
},
but if i add:
async onComment() {
try {
this.$axios.setToken(this.$store.state.token)
let response = await this.$axios.$post(
"/comment/add",
{
...
}
);
} catch (err) {
{...}
}
},
It works fine. Why is this happening?
question from:
https://stackoverflow.com/questions/65647215/nuxtserverinit-not-setting-globally-header-authorization 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…