when I submit the form to the Submit form button, everything works and the uploaded file is logged into the server console, but why does the Multipart: Boundary not found error occur when I click on Submit using fetch
const express = require("express");
var bodyParser = require("body-parser");
const app = express();
const multer = require("multer");
const fileStorageEngine = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./images");
},
filename: (req, file, cb) => {
cb(null, Date.now() "--" file.originalname);
},
});
const upload = multer({ storage: fileStorageEngine });
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(bodyParser.text());
app.get("/", (req, res) => {
res.send(`
<form action="/push" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
<button type="submit">Submit form</button>
<button onclick="send(event)" type="submit">Submit using fetch</button>
</form>
<script>
function send(event) {
event.preventDefault();
let formData = new FormData(event.currentTarget.parentElement);
fetch("/push", {
body: formData,
headers: {
"Content-Type": "multipart/form-data",
},
method: "POST",
}).then((data) => console.log(data));
}
</script>
`);
});
app.post("/push", upload.single("image"), (req, res) => {
console.log(req.file);
});
app.listen(3000);
CodePudding user response:
I suppose you want to upload an image? to do so you will need to pass three parameter in your fetch request uri , type and name in your formdata. as an exemple :
fetch("/push", {
body: {uri :formData.uri ,
type: formData.type,
name: forData.name}
headers: {
"Content-Type": "multipart/form-data",
},
method: "POST",
}).then((data) => console.log(data));
}