簡體   English   中英

在 POST 中上傳文件時,req.body 在 Node js 中為 {}

[英]When uploading a file in POST, req.body is {} in Node js

反應代碼 - 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 代碼 - 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 傳輸而創建的特殊對象,不能用控制台記錄。

您的前端代碼是正確的。 你沒有設置multer。 Multer 實際上是一個中間件,會監聽multipart/form-data [查看文檔][1]

Multer 是一個用於處理 multipart/form-data 的 node.js 中間件,主要用於上傳文件。

Multer 將一個主體對象和一個或多個文件對象添加到請求對象中。 body 對象包含表單文本字段的值,文件或文件對象包含通過表單上傳的文件。

要在 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

然后在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)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM