body-parser 的问题

Issue with body-parser

我的控制台显示输出为 undefined,即使尝试将内容类型设置为 application/json

app.js

const bodyParser = require('body-parser')
app.use('/posts', postRoute)
app.use(bodyParser.json())

型号

const PostSchema = mongoose.Schema({
    title: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    date: {
        type: Date,
        default: Date.now
    }
})

module.exports = mongoose.model('Posts', PostSchema)

路线

router.post('/post', (req, res) => {

    console.log(req.body) //It displays undefined
})

邮递员

试图在 headers 中包含内容类型,但无法显示输出

您必须在注册其他中间件之前使用主体解析器,否则主体解析器将在您的中间件执行后设置 req.body,这就是您将其视为未定义的原因

const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use('/posts', postRoute)

使用最新版本的express,不再需要额外的模块;你可以只使用 build-in JSON module.

const app = express()
app.use(express.json())

app.post('/post', (req, res) => {
  console.dir(req.body)
  res.send('echo')
})

适合我。