Express.js req.body 打印未定义

时间:2021-05-26 18:50:48

标签: javascript node.js express

const  express = require('express')
const userRouter= require('./routes/user.js')
const User = require('./models/user.js')
var bodyParser = require('body-parser')


const app = express();
const port = process.env.PORT || 4200


app.use(bodyParser.urlencoded({
    extended: true
  }));
  
app.use(userRouter)

 const router = new express.Router()

 app.get('/',(req,res)=>{
     debugger
    console.log('Hello')
     res.send('Hello World')
 })



app.post('/clients',async (req,res)=>{
    const user = new User(req.body)
    debugger
    try{
        console.log("body "+req.body)
       var result = await  user.save()
        res.status(201).send(result)
    }catch(e){
        res.status(500).send(e)
    }
})


app.use(router);


app.listen(port,()=>{
    console.log('Server started at'+port)
})

/clients 端点打印 req.body undefined 我已经尝试了所有情况,但仍然无法找到错误

<块引用>

1.used //app.use(express.json) 但对我不起作用

<块引用>
  1. 当我在浏览器控制台中打印 req 时,我无法在 req 对象中找到 body 参数

1 个答案:

答案 0 :(得分:1)

你需要使用

app.use(bodyParser.json());

而不是urlencoded

更多信息 - https://www.npmjs.com/package/body-parser#bodyparserjsonoptions

请设置JSON(application/json) Please select JSON(application/json) as shown in image