简体   繁体   English

Nuxt.js 仅在服务器端获取数据

[英]Nuxt.js Fetching Data only on Server Side

Is there any way to fetch data from an API only on Server-Side in NuxtJS since I will include my API_TOKEN in the headers of the request.有什么方法可以仅在 NuxtJS 的服务器端从 API 获取数据,因为我将在请求的标头中包含我的API_TOKEN

Example Code:示例代码:

<template>
  <div>
    <h1>Data fetched using asyncData</h1>
    <ul>
      <li v-for="mountain in mountains" :key="mountain.title">
        <NuxtLink
          :to="{ name: 'mountains-slug', params: { slug: mountain.slug } }"
        >
          {{ mountain.title }}
        </NuxtLink>
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  async asyncData({ $http }) {
    const mountains = await $http.$get('https://api.nuxtjs.dev/mountains', {headers: "X-API-KEY: MY_API_TOKEN"})
    return { mountains }
  }
}
</script>

You cannot use private keys here because you will reach your server only once, then it will be used only on the client.您不能在此处使用私钥,因为您只会访问您的服务器一次,然后它将仅在客户端上使用。 Either use a middleware to hide the token or use a public one.要么使用中间件来隐藏令牌,要么使用公共的。

My other answer on this subject can be useful here.我关于这个主题的其他答案在这里很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM