【发布时间】:2021-08-07 16:50:42
【问题描述】:
我在Postman post 请求express 服务器代码时收到TypeError: Cannot read property &#39;message&#39; of undefined<br> &nbsp; &nbsp; 错误。
Server.js
const express = require('express');
const {v4: uuidv4} = require('uuid');
const app = express();
// Middleware for data on post request
app.use(express.json({extended: false}));
// Data
const todos = [
{
message: "Buy tea",
id: 1
},
{
message: "Buy wrp for lunch",
id: 2
},
{
message: "Play game",
id: 3
}
];
/* --------- API ---------- */
app.get("/", (req, res) => {
res.status(200).json(todos);
})
app.post("/", (req, res) => {
const newtodo = {
message: res.body.message,
id: uuidv4()
}
todos.push(newtodo);
res.status(201).json(todos);
})
const PORT = process.env.PORT || 5001;
app.listen(PORT, () => {
console.log(`Server running on port: ${PORT}`);
} );
在Headers 我有Key Content-type Value application/json。但我不断收到错误。截图如下:
似乎无法确定问题所在。 Message 在我的 server.js 文件中定义。
【问题讨论】:
-
可能是
res.body未定义,因此没有名为message的属性 - 也许您的意思是req.body.task... 因为这就是您要发送的内容 -
@Bravo 实际上我正在使用
task作为属性而不是message进行测试。所以上传了错误的截图。现在更正了。 “可能是 res.body 未定义,” - 但我在postman上定义了body。你可以在截图上看到。 -
是的,您已经设置了 request 的正文 - 我确实说过 - 但您正在尝试读取 request 的正文b>响应(它们不是一回事)
-
@Bravo 是的,你是对的。请将其添加为答案。
-
就我而言,这是一个错字 - 当然你在阅读请求时没有故意使用响应而不是请求
标签: javascript node.js express postman uuid