简体   繁体   English

Express:使用 post 方法未定义的主体

[英]Express : Body undefined with post method

I'm trying to get data from a post request using express.我正在尝试使用 express 从发布请求中获取数据。 But when I use Postman to create the resquest, the req.body is empty (console.log shows 'req {}') I tried a couple of things and read similar questions in StackOverflow but I couldn't solve my issue.但是当我使用 Postman 创建请求时,req.body 是空的(console.log 显示'req {}')我尝试了几件事并在 StackOverflow 中阅读了类似的问题,但我无法解决我的问题。

Here are two screens of my Postman request using form-data and raw: postman request postman form For the second, I also tried with the default content-type before adding application/json这是我的 Postman 使用表单数据和原始请求的两个屏幕: postman 请求postman 表单对于第二个,我还尝试在添加 application/json 之前使用默认内容类型

Thanks for your help !谢谢你的帮助 !

// File : router.js

import express from 'express'

const router = express.Router()

// I tried some router.get routes here and it works with no problem...

router.post('/myurl', (req, res) => {
    console.log('req', req.body)
})

export default router



// File : app.js


import express from 'express';

import router from './router.js';

const app = express();
const port = 3000;

app.use(express.json())
app.use(express.urlencoded({ extended: true }))

app.use('/', router)

app.listen(port, () => {
    console.log(`App listening at http://localhost:${port}`);
}
);

You need three elements of the request and server side code to match.您需要请求和服务器端代码的三个元素相匹配。

  • The Content-Type request header must specific the format you are sending the data in Content-Type请求 header 必须指定您发送数据的格式
  • The request body must be encoded to match that header (and be valid)请求正文必须经过编码以匹配 header(并且有效)
  • The server needs body parsing middleware that supports that format.服务器需要支持该格式的正文解析中间件。

Your first screenshot shows you are POSTing raw data which is invalid JSON. It does not show what Content-Type request header you are including.您的第一个屏幕截图显示您正在发布无效的原始数据 JSON。它没有显示您包含Content-Type请求 header。

You need to make the JSON valid and ensure that you have Content-Type: application/json in the request headers.您需要使 JSON 有效并确保请求标头中有Content-Type: application/json


Your second screenshot shows that you are posting multipart/form-data , but you only have middleware that parses application/json and application/x-www-form-urlencoded data.您的第二个屏幕截图显示您正在发布multipart/form-data ,但您只有解析application/jsonapplication/x-www-form-urlencoded数据的中间件。

Either change the format you are POSTing in, or add suitable middleware.要么更改您发布的格式,要么添加合适的中间件。

Note also that the Content-Type of the individual parts is wrong.另请注意,各个部分的 Content-Type 是错误的。 example is not valid JSON ( 100 is valid JSON but you probably don't want it to be treated as such). example is not valid JSON ( 100有效 JSON 但您可能不希望它被这样对待)。


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

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