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) 但对我不起作用
<块引用>答案 0 :(得分:1)
你需要使用
app.use(bodyParser.json());
而不是urlencoded
更多信息 - https://www.npmjs.com/package/body-parser#bodyparserjsonoptions