Nuxt:仅在服务器端获取数据 [英] Nuxt: Fetching data only on server side

查看:72
本文介绍了Nuxt:仅在服务器端获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Github 的 API 来获取固定存储库的列表,并将调用放入 AsyncData 方法中,以便在第一次渲染时获得该列表.但我刚刚了解到 AsyncData 在 ServerSide 上调用一次,然后每次在客户端上加载页面.这意味着客户端不再拥有进行 API 调用的令牌,无论如何,我不会让我的 Github 令牌在客户端中.

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,
    };
  },
});

推荐答案

您应该将 Vuex 与 nuxtServerInit 一起使用.

You should use Vuex with nuxtServerInit.

nuxtServerInit 将始终在第一页加载时触发,无论您在哪个页面上.所以你应该先导航到 store/index.js.

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

然后你创建一个状态:

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

现在您创建了刷新页面时始终执行的操作.即使在服务器端,Nuxt 也可以访问商店.

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

您可以将令牌存储在 cookie 中.Cookie 位于客户端,但 nuxtServerInit 有第二个参数.请求 req.有了它,您就可以访问标题,并且还有您的 cookie.

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;

这篇关于Nuxt:仅在服务器端获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆