gpt4 book ai didi

javascript - 使用 getServerSideProps 获取内部 API? (Next.js)

转载 作者:行者123 更新时间:2023-12-05 00:23:58 24 4
gpt4 key购买 nike

我是 Next.js 的新手,我正在尝试了解建议的结构并处理页面或组件之间的数据。
例如,在我的页面内 home.js ,我获取了一个名为 /api/user.js 的内部 API它从 MongoDB 返回一些用户数据。我通过使用 fetch() 来做到这一点从 getServerSideProps() 内调用 API 路由,它经过一些计算将各种 Prop 传递给页面。
据我了解,这对 SEO 有好处,因为 Prop 在服务器端被获取/修改,并且页面让它们准备好呈现。但后来我在 Next.js 文档中读到你不应该使用 fetch()getServerSideProps() 中的所有 API 路由.那么我应该怎么做才能遵守良好的做法和良好的 SEO?
我没有对 home.js 进行所需计算的原因在 API 路由本身中,我需要来自这个 API 路由的更多通用数据,因为我也会在其他页面中使用它。
我还必须考虑缓存,客户端使用 SWR 获取内部 API 非常简单,但服务器端我还不确定如何实现它。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.

最佳答案

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 访问数据库.请注意,这仅适用于对内部 API 路由的调用——从 getServerSideProps 调用外部 API 非常好。 .
来自 Next.js getServerSideProps 文档:

It can be tempting to reach for an API Route when you want to fetchdata from the server, then call that API route fromgetServerSideProps. This is an unnecessary and inefficient approach,as it will cause an extra request to be made due to bothgetServerSideProps and API Routes running on the server.

(...) Instead, directly import the logic used inside your API Routeinto getServerSideProps. This could mean calling a CMS, database, orother API directly from inside getServerSideProps.


(注意 the same applies when using getStaticProps / getStaticPaths methods )

这是一个小的重构示例,它允许您在 getServerSideProps 中重用来自 API 路由的逻辑。 .
假设您有这个简单的 API 路由。
// 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 路由中使用。
// 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)
}
而且还可以让你重复使用 getData getServerSideProps中的函数.
// pages/home
import { getData } from './api/user'

//...

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

关于javascript - 使用 getServerSideProps 获取内部 API? (Next.js),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65752932/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com