[英]How to send JSON object from express server to next js page?
I am new to next js and express I am trying to send post data from the server to the client which in this case is my web browser. 我是下一个js的新手,表示我正在尝试将发布数据从服务器发送到客户端(在这种情况下是我的Web浏览器)。 I am able to receive data on the server, now I want to send this data to the respective page. 我现在可以在服务器上接收数据,现在我想将此数据发送到相应的页面。 Following is the code for my server.js file:- 以下是我的server.js文件的代码:-
const express = require('express')
const next = require('next')
const port = parseInt(process.env.PORT, 10) || 3000
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
server.use(express.json());
server.post("/posts", (req, res) => {
req.body.data
res.send(req.body.data);
console.log("Post data : ",req.body.data)
});
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
Now I would like to send req.body.data to the posts page. 现在,我想将req.body.data发送到帖子页面。 How do we do this using nextjs? 我们如何使用nextjs做到这一点? Any help or suggestion is appreciated.Thanks. 任何帮助或建议,表示赞赏。
响应的json方法可用于直接发送json。
res.json(req.body.data);
Create an endpoint in your Express application that returns the data to the client via res.json()
在Express应用程序中创建一个终结点,该终结点通过res.json()
将数据返回给客户端。
Then access it from your React application (probably in the getInitialProps method) by making an Ajax request to it. 然后通过对它发出Ajax请求,从您的React应用程序(可能在getInitialProps方法中)对其进行访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.