【问题标题】:TypeError: Cannot read property &#39;message&#39; of undefined<br> &nbsp; &nbsp;类型错误:无法读取未定义的属性“消息”<br>
【发布时间】:2021-08-07 16:50:42
【问题描述】:

我在Postman post 请求express 服务器代码时收到TypeError: Cannot read property &amp;#39;message&amp;#39; of undefined&lt;br&gt; &amp;nbsp; &amp;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


【解决方案1】:

我认为这里应该是req.body.message 而不是res.body.message

app.post("/", (req, res) => {
const newtodo = {
    message: req.body.message,
    id: uuidv4()
}
todos.push(newtodo);
res.status(201).json(todos);
})

如果我错了,您可以使用像 res?.body?.message 这样的可选链接。

Javascript Optional Chaining

【讨论】:

    猜你喜欢
    • 2014-04-14
    • 1970-01-01
    • 1970-01-01
    • 2020-11-01
    • 1970-01-01
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多