【问题标题】:Postman Form-Data and x-www-form-encoded return null dataPostman Form-Data 和 x-www-form-encoded 返回空数据
【发布时间】:2020-04-18 18:30:55
【问题描述】:

当我将POSTContent_Type 设置为原始/JSON 时,响应不为空。但是当我尝试将Content_Type 设置为表单数据的POST 数据时,响应返回为空。我该如何解决这个问题?

Postman Screenshot with FormData

但是当我尝试作为原始数据/JSON 时,没关系:

Postman Screenshot with JSON Data

对于原始数据,我的内容类型是:

multipart/form-data; boundary=<calculated when request is sent>

我的 cors 设置是:

app.use((req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
  if (req.method === "OPTIONS") {
    res.header("Access-Control-Allow-Methods", "PUT, POST, PATCH, DELETE, GET");
    return res.status(200).json({});
  }
  next();
});

我的后置路由器是这样的:

router.post("/", upload.single("productImage"), (req, res, next) => {
  console.log(req.file);
  Category.findById(req.body.categoryID)
    .then((category) => {
      if (!category) {
        return res.status(404).json({
          message: "Category not found",
          category: category,
        });
      }

      //
      const product = new Product({
        _id: new mongoose.Types.ObjectId(),
        name: req.body.name,
        price: req.body.price,
        quantity: req.body.quantity,
        category: req.body.categoryID,
      });
      return product.save();
    })
    .then((result) => {
      console.log(result);
      res.status(201).json({
        message: "Object created succesfully",
        product: {
          id: result._id,
          name: result.name,
          price: result.price,
          quantity: result.quantity,
          category: result.category,
        },
      });
    })
    .catch((err) => {
      console.log(err), res.status(500).json({ error: err });
    });
});

错误是:

UnhandledPromiseRejectionWarning: Error
[ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the
 client

我该如何解决这个问题?

【问题讨论】:

  • 你能解决问题吗?即使我有同样的问题

标签: node.js mongodb rest express cart


【解决方案1】:

您在表单数据示例中以错误的方式编写 var:正确的方式是 categoryID 而不是 category

【讨论】:

    猜你喜欢
    • 2014-12-30
    • 2021-01-04
    • 2011-04-29
    • 2020-10-06
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多