Reactjs Fastify使用next.js为渲染提供react道具

Reactjs Fastify使用next.js为渲染提供react道具,reactjs,next.js,fastify,Reactjs,Next.js,Fastify,我正在将Next.js的示例服务器与Fastify一起使用并进行实验,我想知道是否有一种方法可以将JSON对象作为道具传递到渲染中?我试图在文档中找到任何东西,但找不到任何可以这样做的东西 我使用的服务器代码是 const fastify = require('fastify')(); const Next = require('next'); const port = parseInt(process.env.PORT, 10) || 3000; const dev = process.en

我正在将Next.js的示例服务器与Fastify一起使用并进行实验,我想知道是否有一种方法可以将JSON对象作为道具传递到渲染中?我试图在文档中找到任何东西,但找不到任何可以这样做的东西

我使用的服务器代码是

const fastify = require('fastify')();
const Next = require('next');

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';

fastify.register((fastify, opts, next) => {
    const app = Next({ dev })
    app.prepare().then(() => {

        fastify.get('/', (req, res) => {
            let object = {"hello": "world"}; // object I want to pass as a prop
            return app.render(req.req, res.res, '/index', req.query).then(() => {
                res.sent = true
            })
        })

        next()
    }).catch(err => next(err))
})

fastify.listen(port, err => {
    if (err) throw err
    console.log(`Ready on http://localhost:${port}`)
})

您的问题并不特定于
fastfy
,而是与所有服务器框架相关

基本思想是将
req
res
对象传递给Next的
getInitialProps

所以你可以把你的数据放在上面

例如,express的响应对象具有特定于此作业的
locals
属性

因此,为了传递数据,将其附加到req/res

fastfy.get('/',(req,res)=>{
const object={hello:'world'};//我想作为道具传递的对象
res.res.myDataFromController=对象;
返回app.render(req.req,res.res,'/index',req.query)。然后(()=>{
res.sent=true;
});
});
///some next page.jsx
const IndexPage=({dataFromGetInitilProps})=>(
{JSON.stringify(dataFromGetInitilProps,null,2)}
);
IndexPage.getInitilProps=ctx=>{
常数{res}=ctx;
//res将仅位于服务器端的上下文中
const dataFromGetInitilProps=res?res.myDataFromController:null;
返回{
dataFromGetInitilProps:res.myDataFromController,
};
};
导出默认索引扩展;