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

查看:141
本文介绍了使用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,该API会从mongodb向我发送一些用户数据.现在,获取操作发生在 getServerSideProps()内部,该操作会在一些数学运算之后将各种道具传递到页面.

For instance inside my home.js page, I fetch a internal API called /api/user.js where it sends back to me some user data from mongodb. The fetch right now happens inside the getServerSideProps() which passes various props to the page after some math.

根据我的理解,这是获得良好SEO的方法,因为道具已获取/修改了服务器端,并且页面已准备好呈现.但是,然后我在Next.js文档中阅读到,在 getServerSideProps() ..内部不应该获取内部API,那么我应该怎么做才能遵守良好实践和良好的SEO?

From my understanding this is the way to go for a good SEO, since props get fetched/modified server side and the page gets em ready to render. But then I read in the Next.js documentation that fetch to internal API shouldn't happen inside the getServerSideProps() .. so what am I suppose to do to comply to good practice and good SEO?

我不同时在/api/user.js中进行home.js数学运算,然后将数据传递给home.js的原因是,因为我需要使用的来自/api/user.js的更多通用数据在其他页面也是如此.

The reason I'm not doing also the home.js math inside the /api/user.js and THEN pass data to home.js, is because I need more generic data from /api/user.js which I use differently in other pages as well.

更不用说缓存方面了,哪一个客户端非常直接地使用SWR来获取内部API,但是服务器端我还不确定如何实现.

Not to mention the caching aspect, which client side is very straight forward 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文档,该内容不应该在getServerSideProps()内部发生.

But then I read in the Next.js documentation that fetch to internal API shouldn't happen inside the getServerSideProps()

您想直接在 getServerSideProps 中使用API​​路由中的逻辑,而不是调用内部API.

You'd want to use the logic that's in your API route directly in getServerSideProps, rather than calling your internal API.

这是一个小的重构示例,允许您在 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天全站免登陆