node.js - POST 请求返回未定义
问题描述
当邮递员的请求使用下面给出的 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
推荐阅读
- pipeline - 是否可以在多阶段构建期间将工件存储到 Circle CI 中?
- php - 在 Google App Engine 中连接到 Google Cloud SQL
- java - How can I find the first commit of a branch with JGit?
- flutter - How to pass parameters to callbacks in flutter?
- php - php中的max_execution_time vs set_time_limit方法
- r - Remove NA strings from table (characters) in R
- xcode - Xcode relative file path
- java - JPA Hibernate,如何在创建时验证并忽略更新时的验证
- javascript - 如何映射多个数组和条件渲染组件
- kubernetes - 有什么方法可以在 Kubernetes 中使用 configmap 从值中读取 hostAliases?