【问题标题】:How to parse request body?如何解析请求正文?
【发布时间】:2021-11-12 06:01:18
【问题描述】:
const express = require('express')
const cors = require('cors')
const app = express()
const PORT = process.env.PORT || 3000;

app.use(cors())

app.use(express.json())
app.use(express.urlencoded({ extended: true }))

app.all('/hello/', function (req, res, next) {
  res.json({
    'message': 'test',
    'x-result': req.headers['x-test'],
    'x-body': req.body
  })
})

app.listen(PORT, function () {
  console.log('CORS-enabled web server listening on port 3000')
})

请求:

curl 'http://127.0.0.1:3000/hello/' -d 'it is body' -H 'x-test: test'

我想得到这个:

{ "message":"test", "x-result":"test", "x-body":"它是正文" }

但是我得到了这个:

{"message":"test","x-result":"test","x-body":{"it is body":""}}

为什么以及如何做正确的事?

【问题讨论】:

标签: node.js express


【解决方案1】:

您应该发送正确的内容类型,在您的情况下是 text/plain。

curl 'http://127.0.0.1:3000/hello/' -H 'content-type: text/plain;' -d 'it is body' -H 'x-test: test'

除了正确的内容类型,您还需要在应用程序中使用express.text()。

app.use(express.text())

【讨论】:

  • 我可以将默认请求内容类型设置为 'text/plain' 以省略“-H 'content-type: text/plain;'”吗?
  • 如果你只使用express.text(),而不使用其他类型,Express 会将请求解析为text/plain,而没有content-type 标头
  • @aaltw 如果这回答了你的问题,你能把它标记为最佳答案吗?
猜你喜欢
  • 2021-06-07
  • 2021-07-09
  • 2022-07-18
  • 1970-01-01
  • 1970-01-01
  • 2019-10-03
  • 2014-06-10
  • 2017-06-01
  • 1970-01-01
相关资源
最近更新 更多