首页 > 解决方案 > 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

标签: node.jsexpressbabeljsbody-parser

解决方案


从 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

推荐阅读