post-router的req.body包含新行和冒号

req.body of post router contains new line and colon?

本文关键字:包含新 req body post-router      更新时间:2024-05-18

我想知道如何从req.body.中提取post数据

我的帖子数据是

{
 name:'asdf',
 completed: false,
 note: 'asdf'
}

当我试图使用JSON.stringify控制台时,我得到了作为的req.body

{"{'n name:'asdf',completed:false,note:'asdf'}":""}

我注意到req.body对象中添加了新行和冒号。所以当我试图过滤req.body.name时,它会返回未定义的结果。

我使用了app.use(bodyParser.json());,但仍然没有得到实际的结果

因此,我想知道以下内容:1.如何过滤帖子对象?2.为什么要在req.body对象中添加新行和冒号?

我自己通过以下方式找到了解决方案请求。张贴时正文为空

当我在rest客户端测试时,我犯的错误是,

  1. 我最初制作的内容类型是:www表单url编码。后来我把它做成了application/json
  2. 我并没有在键值对中使用引号。因此您需要将原始部分中的数据作为进行传递

    {"name":"asdf","已完成":false,"note":"asdf"}

注意:虽然www表单url编码也可以,但当您将表单部分中的数据作为传递时

name      asdf
completed false
note      asdf

所有解析器都接受一个类型选项,该选项允许您更改中间件将解析的内容类型。

// parse various different custom JSON types as JSON 
app.use(bodyParser.json({ type: 'application/*+json' }))
// parse some custom thing into a Buffer 
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
// parse an HTML body into a string 
app.use(bodyParser.text({ type: 'text/html' }))