简体   繁体   English

如何将JSON对象从快递服务器发送到下一个js页面?

[英]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.

相关问题 如何在Next js上将数据从快递服务器发送到客户端? - How to send data from express server to client on Next js? 在Node.js / Express.js中,如何将JSON对象从服务器传输到客户端? - In Node.js/Express.js, how can I transfer a JSON object from server to client? 如何从 for 循环发送 Express JS 中的 res.json() - How to send res.json() in Express JS from a for loop 如何从服务器(Node JS和Express)的客户端上接收和使用JSON对象? - How do I receive and use a JSON object on the client-side from the server (Node JS and Express)? 如何在Express JS中重定向到下一页 - How to redirect to next page in Express js 如何将html数据从html页面发送到node.js服务器 - how to send json data from html page to node.js server 如何从Node.js / Express中的URL获取JSON对象 - How to GET JSON Object from URL in Node.js/Express 如何将对象数组中的文件发送到快递服务器? - How to send a file in array of object to express server? 如何将诸如访问者命中之类的内容从服务器(express.js)传递到 next.js? - How to pass something like visitor hits from server (express.js) to next.js? 在Node.js中使用Express成功后,如何发送JSON响应并重定向到某些html页面? - How to send a JSON response and redirect to some html page after success in Node.js using express?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM