【问题标题】:Request body is empty when posting a postman form-data发布邮递员表单数据时请求正文为空
【发布时间】:2022-01-11 23:17:34
【问题描述】:

我花了一整天的时间试图找出解决这个问题的方法,但我没有。所以我请你帮忙。

我使用表单数据类型的 POST 方法向邮递员发送了一个请求,我在 vscode 中控制了 req.body,控制台显示它是从邮递员发送的对象,它包含正确的数据,没有错误。

   router.post("/addPost/:id", async (req, res) => {
    try {
        console.log(req.body);
        res.send("success");
    } catch (error) {
        console.log(error);
    }
});

然后我重复了相同的参数和相同的步骤,但使用了 PUT 方法,我在 vscode 中控制了 req.body,但这里控制台显示了一个空的 req.body 对象。

   router.put("/edit/:id", async (req, res) => {
try {
    console.log(req.body);
    res.send("success");
} catch (error) {
    console.log(error);
}});

module.exports = router;

main.js 文件

const express = require("express");
const mongoose = require("mongoose");
const app = express();
app.use(express.json());
const URI = process.env.URI;
mongoose
.connect(URI, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
    useFindAndModify: false,
})
.then(() => console.log("Connected to DB"))
.catch((error) => console.log(error));
app.use("/api/user", require("./routes/user/user"));
app.use("/api/admin", require("./routes/admin/admin"));
app.listen(5000, () => console.log(`server up and running`));

请帮帮我。

【问题讨论】:

  • 如果你能分享代码sn-p,更容易更快地回答问题。没有代码,我可以在这里想到两种可能的情况。 1)你在你的代码中使用了bodyparser吗? 2) 由于是 PUT 请求,没有 content-length 头可能表示没有请求体。
  • 可以分享一下main.js吗?

标签: node.js postman form-data


【解决方案1】:

我认为这是因为表单数据不适用于 PUT 请求。传统上,表单数据仅适用于 GET 和 POST 请求。 您可以进行变通以使其在 PUT 请求中工作。

  1. 添加 Content-Type 和 Content-Length 标头以指示存在请求正文。
  2. 使用 bodyParser 中间件。

当需要处理表单数据时,最好使用 POST 请求。

【讨论】:

  • 那条路线上的 POST 也有同样的问题,我真的不明白为什么,它与我的其他代码一起无法正常工作!
【解决方案2】:

您正在使用默认不支持的 put 请求,使其成为 POST 请求并添加 _method => 'PUT' 以及您传递的数据

【讨论】:

    猜你喜欢
    • 2019-10-22
    • 1970-01-01
    • 2018-09-15
    • 2021-11-25
    • 1970-01-01
    • 2021-08-12
    • 2021-08-25
    • 2018-07-12
    • 1970-01-01
    相关资源
    最近更新 更多