Nuxt: Fetching data only on server side

不羁岁月 提交于 2021-01-28 03:29:42

问题


I am using Github's API to fetch the list of my pinned repositories, and I put the call in the AsyncData method so that I have the list on the first render. But I just learnt that AsyncData is called once on ServerSide, then everytime the page is loaded on the client. That means that the client no longer has the token to make API calls, and anyways, I wouldn't let my Github token in the client.

And when I switch page (from another page to the page with the list) the data is not there I just have the default empty array

I can't figure out what is the best way to be sure that my data is always loaded on server side ?

export default defineComponent({
  name: 'Index',
  components: { GithubProject, Socials },
  asyncData(context: Context) {
    return context.$axios.$post<Query<UserPinnedRepositoriesQuery>>('https://api.github.com/graphql', {
      query,
    }, {
      headers: {
        // Token is defined on the server, but not on the client
        Authorization: `bearer ${process.env.GITHUB_TOKEN}`,
      },
    })
      .then((data) => ({ projects: data.data.user.pinnedItems.nodes }))
      .catch(() => {});
  },
  setup() {
    const projects = ref<Repository[]>([]);

    return {
      projects,
    };
  },
});

回答1:


You should use Vuex with nuxtServerInit.

nuxtServerInit will fire always on first page load no matter on what page you are. So you should navigate first to store/index.js.

After that you create an state:

export const state = () => ({
  data: []
})

Now you create the action that is always being executed whenever you refresh the page. Nuxt have access to the store even if its on the server side.

Now you need to get the data from the store in your component:

export const actions = {
  async nuxtServerInit ({ state }, { req }) {
    let response = await axios.get("some/path/...");
    state.data = response.data;
  }
}

You can store your token in an cookie. Cookies are on the client side but the nuxtServerInit has an second argument. The request req. With that you are able to access the headers and there is your cookie aswell.

let cookie = req.headers.cookie;




回答2:


Wrap your request in if(process.server) within the asyncData method of the page.

If you absolutely require the server-side to call and cannot do it from the client side, then you can just manipulate the location.href to force the page to do a full load.



来源:https://stackoverflow.com/questions/61354470/nuxt-fetching-data-only-on-server-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!