Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 views
in Technique[技术] by (71.8m points)

javascript - NuxtServerInit not setting globally header authorization?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...