在帖子中上传文件时,req.body在节点JS中是{}

发布于 2025-02-13 20:58:19 字数 1531 浏览 0 评论 0原文

react Code -fileUploader.js

// React - FileUplader.js

    const handleSubmission = (e) => {
        e.preventDefault();
        if(isSelected === false){
            alert("load the file");
        }
        else{
            const formData = new FormData();
            formData.append("certificate",selectFile);

            // API CALL
            fetch("http://localhost:8080/upload", {
                method: "POST",
                body: formData,
                headers : {
                    "Content-Type" : "multipart/form-data"
                }
            }).then((response) =>response.json())
            .then((result)=>{
                console.log("Success : ", result);
            })
                .catch((error)=>{
                    console.error("Error : ",error);
                });
        }
    };

nodejs code -server.js

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

app.post('/upload', async function(req ,res){
    try {
        const file = req.files; // undeifined
        const bodyData = req.body; // {}
        console.log("file : ",file);
        console.log("bodyData : ",bodyData);

        res.status(200).send({
            message: "FILE RECEIVED!"
        });
    } catch(error){
        res.send("ERROR")};
});

问题

为什么req.body在节点js中{}

我尝试使用multer,但得到了相同的结果

mdn表示formdata对象不是一个简单的对象,而是为xmlhttprequest创建的特殊对象传输,无法使用控制台记录。

React code - FileUploader.js

// React - FileUplader.js

    const handleSubmission = (e) => {
        e.preventDefault();
        if(isSelected === false){
            alert("load the file");
        }
        else{
            const formData = new FormData();
            formData.append("certificate",selectFile);

            // API CALL
            fetch("http://localhost:8080/upload", {
                method: "POST",
                body: formData,
                headers : {
                    "Content-Type" : "multipart/form-data"
                }
            }).then((response) =>response.json())
            .then((result)=>{
                console.log("Success : ", result);
            })
                .catch((error)=>{
                    console.error("Error : ",error);
                });
        }
    };

Nodejs code - Server.js

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

app.post('/upload', async function(req ,res){
    try {
        const file = req.files; // undeifined
        const bodyData = req.body; // {}
        console.log("file : ",file);
        console.log("bodyData : ",bodyData);

        res.status(200).send({
            message: "FILE RECEIVED!"
        });
    } catch(error){
        res.send("ERROR")};
});

Problem

Why req.body is {} in node js

I tried using MULTER but got the same result

MDN says that FormData object is not a simple object, but a special object created for XMLHttpRequest transmission and cannot be recorded with the console.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

〗斷ホ乔殘χμё〖 2025-02-20 20:58:19

您的前端代码正确。您没有设置Multer。 Multer实际上是中间件,将听Multipart/form-data。 [检查文档] [1]

multer是用于处理多部分/form-data的node.js中间件,
主要用于上传文件。

multer在请求中添加一个身体对象和文件或文件对象
目的。身体对象包含文本字段的值
表单,文件或文件对象包含通过
形式。

要在Node.js环境上处理文件,请编写一个中间件:

const multer = require("multer");
const { randomBytes } = require("crypto");

const fileStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "images");
  },
  filename: (req, file, cb) => {
    cb(null, randomBytes(4).toString("hex") + "-" + file.originalname);
  },
});

const fileFilter = (req, file, cb) => {
  if (
    file.mimetype === "image/png" ||
    file.mimetype === "image/jpg" ||
    file.mimetype === "image/jpeg"
  ) {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

module.exports = multer({ storage: fileStorage, fileFilter }).single("image"); //image is the field name

中使用它

const multer = require("./middlewares/multer");

app.use(cors()); 
app.use(bodyParser.json());
app.use(multer);

然后在Express App app.use(BodyParser.urlencer.urlencoded({Extended:true})

。 [1]: http://expressjs.com/en/resources/middleware/multer.html#:~: text=multer%20IS%20A%20A%20Node.smultipart%2fform%2fform%2fform%2ddata%20%20 )。

Your front end code is correct. You did not set up multer. Multer is actually a middleware, will be listening to multipart/form-data. [check the docs][1]

Multer is a node.js middleware for handling multipart/form-data, which
is primarily used for uploading files.

Multer adds a body object and a file or files object to the request
object. The body object contains the values of the text fields of the
form, the file or files object contains the files uploaded via the
form.

to handle files on node.js environment, write a middleware:

const multer = require("multer");
const { randomBytes } = require("crypto");

const fileStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "images");
  },
  filename: (req, file, cb) => {
    cb(null, randomBytes(4).toString("hex") + "-" + file.originalname);
  },
});

const fileFilter = (req, file, cb) => {
  if (
    file.mimetype === "image/png" ||
    file.mimetype === "image/jpg" ||
    file.mimetype === "image/jpeg"
  ) {
    cb(null, true);
  } else {
    cb(null, false);
  }
};

module.exports = multer({ storage: fileStorage, fileFilter }).single("image"); //image is the field name

Then use it in express app

const multer = require("./middlewares/multer");

app.use(cors()); 
app.use(bodyParser.json());
app.use(multer);

app.use(bodyParser.urlencoded({extended : true}));

[1]: http://expressjs.com/en/resources/middleware/multer.html#:~:text=Multer%20is%20a%20node.,multipart%2Fform%2Ddata%20).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文