在 next.js 的 getInitialProps 中使用后端数据渲染页面
Render page with backend data to be used in getInitialProps in next.js
我是 next.js 的新手。我需要在我的 next.js 项目中实现的是连接到数据库,获取一些数据,使用 express 处理它并在我的应用程序的客户端使用它。我将在快速路由处理程序中连接到数据库。问题:是否可以将下载的数据传递给客户端(即传递给 getInitialProps
生命周期方法)而不从 for.ex.fetch
api 中获取它(使用 for.ex.fetch
api) =11=],即。有没有办法让它已经准备好通过一些道具在客户端消费(没有经典的获取方法)?
您可以使用与此类似的方式使用 express 获取数据,在 express 中:
server.get('/your/route', async (req, res) => {
// fetch your data
let data = await fetch(....)
return app.render(req, res, '/yourpage',data)
})
然后在 getInitialProps
中您可以访问您的数据:
static async getInitialProps (context) {
let data = context.query;
return {data}
}
我是 next.js 的新手。我需要在我的 next.js 项目中实现的是连接到数据库,获取一些数据,使用 express 处理它并在我的应用程序的客户端使用它。我将在快速路由处理程序中连接到数据库。问题:是否可以将下载的数据传递给客户端(即传递给 getInitialProps
生命周期方法)而不从 for.ex.fetch
api 中获取它(使用 for.ex.fetch
api) =11=],即。有没有办法让它已经准备好通过一些道具在客户端消费(没有经典的获取方法)?
您可以使用与此类似的方式使用 express 获取数据,在 express 中:
server.get('/your/route', async (req, res) => {
// fetch your data
let data = await fetch(....)
return app.render(req, res, '/yourpage',data)
})
然后在 getInitialProps
中您可以访问您的数据:
static async getInitialProps (context) {
let data = context.query;
return {data}
}