Next.js 将数据从NextJS的上一页传递到getServerSideProps

Next.js 将数据从NextJS的上一页传递到getServerSideProps,next.js,server-side-rendering,Next.js,Server Side Rendering,我正在使用NextJS开发一个类似电子商务的网站 我将在/products页面中获取并显示产品列表。单击任何产品后,我将导航到/details/[productId],并按如下方式获取这些产品详细信息 // In /details/[productId].js file export async function getServerSideProps({params}) { const res = await fetch(`https:my-api-url/api/products/$

我正在使用NextJS开发一个类似电子商务的网站

我将在
/products
页面中获取并显示产品列表。单击任何产品后,我将导航到
/details/[productId]
,并按如下方式获取这些产品详细信息

// In /details/[productId].js file

export async function getServerSideProps({params}) {
    const res = await fetch(`https:my-api-url/api/products/${params.productId}`)
    const product = await res.json()
    return {
        props: {
            product
        }
    }
}
问题

直到这一步,一切看起来都很好。但是我想减少数据库读取计数的数量,因此我计划使用上一页(
/products
)中获取的数据,其中将包含有关产品的信息,而不是在
详细信息
页面中再次获取产品详细信息。因此,我需要一种方法将这些产品对象传递到下一个屏幕
/details/[productId]
的getServerSideProps(以实现用于SEO目的的SSR)

解决方法

我目前的一个解决方案是将产品json字符串化,并通过查询参数传递它,然后将其返回到
getServerSideProps({params,query})
。但它只是在浏览器中垃圾邮件发送我的url,看起来一点也不好

期望值

是否有其他方法将数据传递到
getServerSideProps
函数中,以便它利用数据在服务器本身生成整个页面。请引导我克服这个问题。任何帮助都将不胜感激


提前谢谢。。(:

您可以将自定义服务器作为express引入,该服务器提供在应用程序或请求的整个生命周期内可用的属性

const next=require('next');
const express=require('express');
const app=next({dev:process.env.NODE_env!=='production'});
const handle=routes.getRequestHandler(应用程序);
const env=process.env.NODE|env||'dev';
app.prepare()然后(()=>{
const server=express();
server.get('/products',异步(req,reply)=>{
const products=wait/…获取包含详细信息的产品
req.app.locals.products=产品;
返回app.render(请求,回复,'/path/to/products/page',请求查询);
});
server.get('/details/:productId',异步(req,reply)=>{
const{productId}=req.params;
const{products}=req.app.locals;
//使用productId查找产品,并在req.locals中提供
req.locals.product=//产品;
返回app.render(请求,回复,'/path/to/product/detail/page',请求查询)
}); 
server.get('*',(请求,回复)=>{
返回句柄(请求、回复)
});
听(3000);
});
请注意产品列表的增长幅度,以避免应用程序内存不足

您还可以返回一个cookie,其中包含产品请求()中的产品列表。然后在产品详细信息页面上阅读

当我输入URL时http://localhost:3000/blog/wfe436


如果你找到了这个问题的答案,那么请发布它。即使我也被这个问题困住了。@Karthik还没有兄弟,目前我在每个页面上都会点击该服务两次。对这个问题投上一票,这样任何人都会注意到这个问题。但是这种方法似乎有缺陷,因为有人获得了你的/page/[pageId]链接直接来说,将不会有任何数据从某个地方传递,但是。注意:如果我有什么错误,请告诉我,因为我刚刚开始使用nextjs,我不知道它是如何工作的,而且我认为您将使用服务器上容易生成的数据重载请求对象。此外,还将发送一些敏感信息在某些情况下,信息将是一个问题
//getting the meta tags dynamically

export const getServerSideProps = async ({ params }) => {
    // Get external data from the file system, API, DB, etc.
    console.log(params) // here is the data of the url { blogname: 'wfe436' }
    const posts = Data
    // The value of the `props` key will be
    //  passed to the `Home` component
    return {
        props: { posts }
    }
}