node.js - POST 请求返回未定义

标签 node.js express babeljs body-parser

当 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/

相关文章:

mysql - Connect-Mongo 和 Express-session 无法正常工作

javascript - ES6 导出和导入函数

javascript - ES6 : How to Import and Export modules and keep access from console

node.js - MongoDB-Memory-Server 使 jest 测试调试卡在 WSL 上

javascript - 简单的 Express.js 应用程序运行时出错

Mysql根据用户输入过滤查询

typescript - 为什么 Babel 不为 IE11 提供 URLSearchParams polyfill

node.js - 如何使用 Elastic Beanstalk 设置 AWS CDK 的环境变量?

node.js - 包含 'ref' 但未指定类型的 Mongoose 模型属性是什么?

node.js - 使用 Node.js 通过其唯一 _id 更新多个 MongoDB 对象