gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:15:43 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com