简体   繁体   中英

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 contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded() .

The following example shows how to use body-parsing middleware to populate 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. 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).

Which middleware to use depends upon the type of the data in the body (urlEncoded data, JSON data or something else).

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)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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