【发布时间】:2021-04-21 11:26:01
【问题描述】:
我是 Next.js 的新手,我正在尝试了解建议的结构并处理页面或组件之间的数据。
例如,在我的页面home.js 中,我获取了一个名为/api/user.js 的内部API,它从MongoDB 返回一些用户数据。我这样做是通过使用fetch() 从getServerSideProps() 中调用API 路由来实现的,该路由经过一些计算后将各种道具传递给页面。
据我了解,这有利于 SEO,因为道具会在服务器端获取/修改,并且页面可以让它们准备好呈现。但后来我在 Next.js 文档中读到,您不应该将 fetch() 用于 getServerSideProps() 中的所有 API 路由。那么我应该怎么做才能遵守良好的做法和良好的 SEO?
我没有在 API 路由本身中对 home.js 进行所需计算的原因是我需要来自此 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.
【问题讨论】:
标签: javascript node.js next.js server-side-rendering fetch-api