使用 getServerSideProps 获取内部 API?(Next.js) [英] Internal API fetch with getServerSideProps? (Next.js)

查看:48
本文介绍了使用 getServerSideProps 获取内部 API?(Next.js)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Next.js 的新手,我正在尝试了解建议的结构并处理页面或组件之间的数据.

I'm new to Next.js and I'm trying to understand the suggested structure and dealing with data between pages or components.

例如,在我的页面 home.js 中,我获取了一个名为 /api/user.js 的内部 API,它从 MongoDB 返回一些用户数据.我通过使用 fetch()getServerSideProps() 中调用 API 路由来做到这一点,该路由在一些计算后将各种道具传递到页面.

For instance, inside my page home.js, I fetch an internal API called /api/user.js which returns some user data from MongoDB. I am doing this by using fetch() to call the API route from within getServerSideProps(), which passes various props to the page after some calculations.

据我了解,这有利于 SEO,因为道具会在服务器端获取/修改,并且页面让它们准备好呈现.但后来我在 Next.js 文档中读到,您不应该将 fetch() 用于 getServerSideProps() 中的所有 API 路由.那么我应该怎么做才能遵守良好的做法和良好的 SEO?

From my understanding, this is good for SEO, since props get fetched/modified server-side and the page gets them ready to render. But then I read in the Next.js documentation that you should not use fetch() to all an API route in getServerSideProps(). So what am I suppose to do to comply to good practice and good SEO?

我没有在 API 路由本身中对 home.js 进行所需计算的原因是我需要来自此 API 路由的更多通用数据,因为我将在其他页面中使用它作为好吧.

The reason I'm not doing the required calculations for home.js in the API route itself is that I need more generic data from this API route, as I will use it in other pages as well.

我还必须考虑缓存,哪个客户端使用 SWR 来获取内部 API 非常简单,但服务器端我还不确定如何实现它.

I also have to consider caching, which client-side is very straightforward using SWR to fetch an internal API, but server-side I'm not yet sure how to achieve it.

home.js:

export default function Page({ prop1, prop2, prop3 }) {
        // render etc.
}

export async function getServerSideProps(context) {
  const session = await getSession(context)
  let data = null
  var aArray = [], bArray = [], cArray = []
  const { db } = await connectToDatabase()

  function shuffle(array) {
    var currentIndex = array.length, temporaryValue, randomIndex;
    while (0 !== currentIndex) {
      randomIndex = Math.floor(Math.random() * currentIndex);
      currentIndex -= 1;
      temporaryValue = array[currentIndex];
      array[currentIndex] = array[randomIndex];
      array[randomIndex] = temporaryValue;
    }
    return array;
  }

  if (session) {
    const hostname = process.env.NEXT_PUBLIC_SITE_URL
    const options = { headers: { cookie: context.req.headers.cookie } }
    const res = await fetch(`${hostname}/api/user`, options)
    const json = await res.json()
    if (json.data) { data = json.data }

    // do some math with data ...
    // connect to MongoDB and do some comparisons, etc.

推荐答案

但后来我在 Next.js 文档中读到,您不应该将 fetch() 用于 getServerSideProps() 中的所有 API 路由.

But then I read in the Next.js documentation that you should not use fetch() to all an API route in getServerSideProps().

您希望直接在 getServerSideProps 中使用 API 路由中的逻辑,而不是调用您的内部 API.这是因为 getServerSideProps 就像 API 路由一样在服务器上运行(从服务器向服务器本身发出请求是没有意义的).您可以从文件系统读取或直接从 getServerSideProps 访问数据库.

You want to use the logic that's in your API route directly in getServerSideProps, rather than calling your internal API. That's because getServerSideProps runs on the server just like the API routes (making a request from the server to the server itself would be pointless). You can read from the filesystem or access a database directly from getServerSideProps.

(请注意,使用 getStaticProps/getStaticPaths 方法时也是如此)

(Note that the same applies when using getStaticProps/getStaticPaths methods)

这是一个小的重构示例,它允许您在 getServerSideProps 中重用来自 API 路由的逻辑.

Here's a small refactor example that allows you to have logic from an API route reused in getServerSideProps.

假设您有这个简单的 API 路由.

Let's assume you have this simple API route.

// pages/api/user
export default async function handler(req, res) {
    // Using a fetch here but could be any async operation to an external source
    const response = await fetch(/* external API endpoint */)
    const jsonData = await response.json()
    res.status(200).json(jsonData)
}

您可以将获取逻辑提取到一个单独的函数中(如果需要,仍然可以将其保存在 api/user 中),该函数在 API 路由中仍然可用.

You can extract the fetching logic to a separate function (can still keep it in api/user if you want), which is still usable in the API route.

// pages/api/user
export async function getData() {
    const response = await fetch(/* external API endpoint */)
    const jsonData = await response.json()
    return jsonData
}

export default async function handler(req, res) {
    const jsonData = await getData()
    res.status(200).json(jsonData)
}

而且还允许你在getServerSideProps中重复使用getData函数.

But also allows you to re-use the getData function in getServerSideProps.

// pages/home
import { getData } from './api/user'

//...

export async function getServerSideProps(context) {
    const jsonData = await getData()
    //...
}

这篇关于使用 getServerSideProps 获取内部 API?(Next.js)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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