简体   繁体   English

Fastify 使用 next.js 为渲染提供反应道具

[英]Fastify giving a react prop to a render with next.js

I am using Next.js's example server with Fastify and experimenting with it and am wondering if there is a way to pass let's say a JSON object as a prop into a render?我正在使用 Next.js 的示例服务器和 Fastify 并对其进行试验,我想知道是否有办法将 JSON 对象作为道具传递给渲染? I've tried to find anything in the documentation and can't find anything for doing this.我试图在文档中找到任何内容,但找不到任何用于执行此操作的内容。

The server code I'm using is this,我使用的服务器代码是这样的,

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}`)
})

Your question is not specific to Fastify , but relevant for all server frameworks.您的问题并非特定于Fastify ,而是与所有服务器框架相关。

The basic idea is that req & res object are passed to Next's getInitialProps .基本思想是将req & res对象传递给 Next 的getInitialProps

So you can put your data on them.所以你可以把你的数据放在他们身上。

For example, express's Response object has locals attribute that is specific to this job.例如,express 的 Response 对象具有特定于该作业的locals属性。

So, in order to pass data attach it to req / res.因此,为了传递数据,将其附加到 req / res。

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

const IndexPage = ({ dataFromGetInitilProps }) => (
  <div> {JSON.stringify(dataFromGetInitilProps, null, 2)} </div>
);

IndexPage.getInitilProps = ctx => {
  const { res } = ctx;

  // res will be on the context only in server-side
  const dataFromGetInitilProps = res ? res.myDataFromController: null; 

  return {
    dataFromGetInitilProps: res.myDataFromController,
  };
};

export default IndexPage;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM