简体   繁体   English

Express.js:未定义的 request.body

[英]Express.js: undefined request.body

const express = require('express');
const cors = require('cors');

const app = express();
app.use(express.json())
app.use(cors());

app.post('/', (req,res) => {
    console.log(req.body);
    res.send('received')
})

app.listen(5000, console.log('Server is running on port 5000'));

I am trying to send data to the back-end but always getting undefined我正在尝试将数据发送到后端,但总是未定义

在此处输入图像描述

I tried to you a parser but seems like just wrapping void into an object我试过给你一个解析器,但似乎只是将 void 包装成 object

在此处输入图像描述

Posting as answer from my comment.作为我评论的答案发布。

In the second image in postman you need to change the type dropdown from text to JSON, express.json() only parses the body when the header Content-type is set to "application/JSON" and changing that dropdown will automatically include that header.在 postman 中的第二张图片中,您需要将类型下拉列表从文本更改为 JSON,express.json() 仅在 header Content-type 设置为“application/JSON”时解析正文,并且更改该下拉列表将自动包含 header .

Here are the docs if it helps explain why you get the empty object in the second image这是文档,如果它有助于解释为什么你在第二张图片中得到空的 object

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM