【问题标题】:Axios Post Request Sending UndefinedAxios Post 请求发送未定义
【发布时间】:2021-06-08 08:30:12
【问题描述】:

我在将数据从 Axios 发布请求发送到我的 ExpressJS 发布路由时遇到问题。当我尝试读取在发布路线上发送的数据时,它显示为未定义。这是我的 Axios 帖子:

axios.post('http://localhost:3000/temps/heating', {
    messageType: 'heating',
    toggle: 'on'
}).then(res => {
    console.log(res);
}).catch(e => {
    console.log(e)
})

这是我下面的 ExpressJS Post 路由。我尝试使用req.params req.body & req.messageType

routes.post('/heating', (req, res, next) => {
    const messageType = req.data;
    console.log(messageType);
})

我以为是因为 Axios 正在发送“数据”,所以我在 NodeJS 的 post 路由上请求数据?

谢谢

【问题讨论】:

  • 你可以尝试打印'req',看看你会得到什么。你应该有 req.messageType
  • 您的 Express 应用是否使用 body-parser 或类似名称?

标签: node.js reactjs rest axios api-design


【解决方案1】:

看起来您正在节点应用程序中使用 express.js。如果是这样,那就是const messageType = req.body.messageType

【讨论】:

  • 您好,感谢您的回复。我试过了,但得到一个 TypeError: Cannot read property 'messageType' of undefined。有什么建议吗?
  • 您需要在nodejs+ expressjs中添加body-parser,以便在nodejs中提取json数据并使用req.body.messageType获取值。 npmjs.com/package/body-parser
【解决方案2】:

在您的快递应用中确保使用body-parser:https://expressjs.com/en/resources/middleware/body-parser.html

const bodyParser = require('body-parser');
app.use(bodyParser.json());

在您的路线中,您应该能够访问req.body.messageType

routes.post('/heating', (req, res, next) => {
    const messageType = req.body.messageType;
    console.log(messageType);
})

【讨论】:

    猜你喜欢
    • 2020-10-26
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    • 2020-06-05
    • 2020-12-06
    • 1970-01-01
    相关资源
    最近更新 更多