简体   繁体   English

如何在Next js上将数据从快递服务器发送到客户端?

[英]How to send data from express server to client on Next js?

I have a next js web app with express. 我有一个带有Express的下一个js网络应用程序。 I want to post data to this webpage fetch it on my server and pass it on to my next js page. 我想将数据发布到此网页上,以在服务器上获取它,并将其传递给下一个js页面。 I am new to next js and express. 我是下一个js的新手并表示。 Following is my server.js code:- 以下是我的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
    console.log("Post data : ",req.body.data)
    console.log("JSON Response : ",res.json());
  });

  // server.get('/posts/', (req, res) => {
  //   console.log("Post data again : ",res.body.data)
  //   return app.render(req, res, '/posts', { id: "Pritam" })
  // })

  server.get('*', (req, res) => {
    return handle(req, res)
  })

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

When I use get request I am able to send data from my server to the client using return app.render(req, res, '/posts', { name: "Pritam" }) but when I try to do the same thing with post I am not able to receive any data on my client. 当我使用get请求时,我可以使用return app.render(req,res,'/ posts',{name:“ Pritam”})将数据从服务器发送到客户端,但是当我尝试执行相同的操作时发布后,我无法在客户端上接收任何数据。 Initially, I have tried passing values in query params and it works fine. 最初,我尝试在查询参数中传递值,并且工作正常。 Following is my posts.js code:- 以下是我的posts.js代码:-

import React, { Component } from 'react'

class Posts extends Component {
  static async getInitialProps ({ query: { id } }) {
    console.log("Response is ")
    return { postId: id }
  }
  render () {
    return (
      <div>
        <p>Post data {this.props.postId}</p>
      </div>
    )
  }
}


export default Posts;

As suggested by @JasperBernales I made the following changes to my server.js:- 如@JasperBernales所建议,我对server.js进行了以下更改:-

  server.post("/api/agreement", (req, res) => {
    req.body.data
    res.send("ESAnup")
    console.log("Post data agreement: ",req.body.data)
    console.log("JSON Response agreement : ",res.json());
  });

And I have also created a directory for api/agreement.js which contains the following code:- 而且我还为api / agreement.js创建了一个目录,其中包含以下代码:-

export default function handle(req, res) {
  console.log("Request Body",req.body.data) // The request body
  console.log("Request Query :",req.query) // The url querystring
   console.log(req.cookies) // The passed cookies
   res.json({ title: 'Hello World JSON' })
   res.end('Hello World')
}

I am able to see my server response but I am still not able to fetch it on my client. 我能够看到我的服务器响应,但是仍然无法在客户端上获取它。 I am trying to test it on Postman. 我正在尝试在邮递员上进行测试。

I would like to create an endpoint from my server code to send data to my client and receive that data in getInitialProps and render it on my client side. 我想从服务器代码创建一个端点,以将数据发送到客户端,并在getInitialProps中接收该数据并将其呈现在客户端上。 Any help or suggestion is much appreciated.Thank you. 非常感谢您的任何帮助或建议。

checkout api routes supported in nextjs 9. nextjs 9支持的检出api路由

Basically you need to create a folder named api under pages folder. 基本上,您需要在pages文件夹下创建一个名为api文件夹。

example you have a file named sample.js inside the folder 例如,您在文件夹中有一个名为sample.js的文件

export default function handle(req, res) {
  console.log(req.body) // The request body
  console.log(req.query) // The url querystring
  console.log(req.cookies) // The passed cookies
  res.end('Hello World')
}

then each file inside this folder will be called as route and you can call it as /api/sample in your client. 那么此文件夹中的每个文件都将称为路由,您可以在客户端中将其称为/api/sample

暂无
暂无

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

相关问题 如何将JSON对象从快递服务器发送到下一个js页面? - How to send JSON object from express server to next js page? 在node.js和express中,客户端应如何向服务器发送多达3k的大量数据? - In node.js and express, how should a client send a large, up to 3k, amount of data to the server? 如何使用 Node.js express 从服务器向客户端发送实时 stream 响应 - How to send real time stream response from server to client using Node.js express 如何使用 Node.js express 从服务器向客户端发送实时响应 - How to send real time response from server to client using Node.js express 如何使用 Pusher 将用户的存款和取款详细信息从客户端发送到 Node.js(快递)服务器? - How to send deposit and withdraw details of user from client to Node.js (express) server using Pusher? 从服务器向客户端发送数据。 节点JS,快递 - Send data from server to client. NodeJS, Express 如何将数据从bone.js的客户端传递到服务器。 Express + Backbone.js - How to pass the data from backbone.js's client to server. Express + Backbone.js 如何从 url 获取远程 PDF 并使用 Express js 发送到客户端? - How to fetch remote PDF from a url and send to the client with Express js? 如何使用Express(NodeJS)从服务器向客户端发送大量文件 - How to send a lot of files from server to client using express (NodeJS) Express.js - 如何使用 res.render 从 Express 向客户端发送警报? 不重新发送 - Express.js - How to send alert from Express to Client using res.render? Not res.send
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM