【问题标题】:Express : Body undefined with post methodExpress : Body undefined with post 方法
【发布时间】:2022-11-28 21:28:17
【问题描述】:

我正在尝试使用 express 从发布请求中获取数据。但是当我使用 Postman 创建请求时,req.body 是空的(console.log 显示'req {}') 我尝试了几件事并在 StackOverflow 中阅读了类似的问题,但我无法解决我的问题。

这是我使用 form-data 和 raw 的 Postman 请求的两个屏幕: postman request postman form 第二,我在添加 application/json 之前也尝试使用默认的内容类型

谢谢你的帮助 !

// 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}`);
}
);

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:

    您需要请求和服务器端代码的三个元素相匹配。

    • Content-Type 请求标头必须指定您发送数据所采用的格式
    • 请求正文必须经过编码以匹配该标头(并且有效)
    • 服务器需要支持该格式的正文解析中间件。

    您的第一个屏幕截图显示您正在发布原始数据无效的JSON。它不显示您包含的 Content-Type 请求标头。

    您需要使 JSON 有效并确保请求标头中包含 Content-Type: application/json


    您的第二个屏幕截图显示您正在发布multipart/form-data,但您只有解析application/jsonapplication/x-www-form-urlencoded数据的中间件。

    要么更改您发布的格式,要么添加合适的中间件。

    另请注意,各个部分的 Content-Type 是错误的。 example 不是有效的 JSON(100 是有效的 JSON,但您可能不希望它被这样对待)。


    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      • 2021-06-19
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      • 2018-03-08
      相关资源
      最近更新 更多