当 postman 使用下面给出的 json 发起请求时,我得到 hello undefined
作为响应。
请求json
{
"name":"test"
}
我的中间件
import express from 'express';
import bodyParser from 'body-parser';
const app = express();
app.use(bodyParser.json());
app.get('/hello', (req, res)=>{
return res.send("hello");
});
app.post('/hello', (req, res)=>{
console.log(req.body);
return res.send(`hello ${req.body.name}`);
})
app.listen(8000, () => console.log('listening on port 8000'));
使用以下命令启动服务器
npx babel-node src/server.js
最佳答案
从express 4.16.0开始你可以使用app.use(express.json());从请求中获取 json 数据,在您的情况下是这样。您不需要使用 bodyparser 等。
const app = express();
app.use(bodyParser.json()); // remove this
app.use(express.json())// add this line
关于node.js - POST 请求返回未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56714600/