简体   繁体   English

postman 中的表单数据发送空 object 到 node.js

[英]form-data in postman sending Empty object to node.js

I know this has been asked multiple times, but I have been looking around and still can't find an answer to my problem.我知道这已被多次询问,但我一直在环顾四周,但仍然找不到问题的答案。

index.js file index.js 文件

const express = require("express");
require("dotenv").config({
  path: ".env",
});
const PORT = process.env.PORT || 5000;
const runDatabase = require("./config/database");
const path = require('path')

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

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

app.use("/uploads", express.static(path.join(__dirname, "uploads")));

// routers
const userRouter = require("./router/usersRouter");
const categoryRouter = require("./router/categoryRouter");
const productRouter = require("./router/productRouter");

app.use("/api", userRouter);
app.use("/api", categoryRouter);
app.use("/api", productRouter);

app.listen(PORT, () => {
  runDatabase();
  console.log(`🚀The Backend Server is up and running on port ${PORT}🚀`);
});


controller file controller 档案

exports.createCategory = async (req, res) => {
  try {
    const { title, sort } = req.body;
    console.log(req.body); // print empty object

    await categoryModel.create({
      title,
      sort,
    });
    return res.status(200).send("created");
  } catch (err) {
    return res.status(400).send(err.message);
  }
};

Here is my code, when sending the request in JSON raw postman a response is what I need but when using a form-data it will return an empty body这是我的代码,当在 JSON raw postman 中发送请求时,我需要一个响应,但是当使用表单数据时,它将返回一个空主体

this is happened when I send data with form-data returned an empty body这是在我发送带有表单数据的数据返回空体时发生的在此处输入图像描述

this is happened when I send data with raw (Json) returned what i need当我用原始 (Json) 发送数据返回我需要的时,就会发生这种情况在此处输入图像描述

If you use the option "x-www-form-urlencoded" I guess it will work.如果您使用"x-www-form-urlencoded"选项,我想它会起作用。 So here is the thing:所以事情是这样的:

  • When you are using postman's "form-data" it will be considered as multipart/form-data for which you need a library to parse form-data such as multer.当您使用邮递员的"form-data"时,它将被视为multipart/form-data ,您需要一个库来解析表单数据,例如 multer。

  • For x-www-from-urlencoded raw data, you can parse the data using the express built-in middlewares or use a body-parser.对于x-www-from-urlencoded原始数据,您可以使用 express 内置中间件或使用主体解析器解析数据。

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

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