简体   繁体   English

如何从 Get Request In Express 中获取正文?

[英]How Do I Get Body From Get Request In Express?

My Code Returns Invalid Text When I Try To Do It.当我尝试执行此操作时,我的代码返回无效文本。

app.post("/charge", (req, res) => {
    console.log(req.body)
})

As the doc for req.body says:正如req.body的文档所说:

req.body contains key-value pairs of data submitted in the request body. req.body包含在请求正文中提交的数据键值对。 By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded() .默认情况下,它是未定义的,并且在您使用诸如express.json()express.urlencoded()之类的正文解析中间件时填充。

The following example shows how to use body-parsing middleware to populate req.body.以下示例展示了如何使用正文解析中间件来填充 req.body。

By default, the body of the request is not yet read from the incoming stream and therefore it is not yet parsed into req.body either.默认情况下,尚未从传入的 stream 读取请求的主体,因此它也尚未解析为req.body To get it read and parsed into req.body , you have to use some appropriate middleware that will do that for you (or you could do it manually yourself, but it's generally easier to use pre-written middleware that does the job for you).要将其读取并解析为req.body ,您必须使用一些适当的中间件来为您执行此操作(或者您可以自己手动完成,但使用为您完成工作的预先编写的中间件通常更容易) .

Which middleware to use depends upon the type of the data in the body (urlEncoded data, JSON data or something else).使用哪个中间件取决于正文中数据的类型(urlEncoded 数据、JSON 数据或其他数据)。

Here's the example from the doc:这是文档中的示例:

var express = require('express')

var app = express()

app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

app.post('/profile', function (req, res, next) {
  console.log(req.body)
  res.json(req.body)
})

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

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