How can I access the files in the API?
I read the other solutions and all of them require npm packages to solve this. I want to understand why I can't do it vanilla. Also, the answers are old and recommend using body-parser, which now comes bundled with Express.
I would like the solution to be vanilla JS in order to understand the process better.
client
async function uploadFile(file) {
let formData = new FormData();
formData.append("file", file);
let res = await fetchPostFile("/api/files", formData);
}
fetch
export async function fetchPostFile(url, formData) {
try {
let result = await (
await fetch(url, {
method: "POST",
withCredentials: true,
credentials: "include",
headers: {
Authorization: localStorage.getItem("token"),
Accept: "application/json",
"Content-type": "multipart/form-data",
},
body: formData,
})
).json();
return result;
} catch (err) {
return err;
}
}
api
router.post("/api/files", async function (req, res, next) {
try {
console.log(req.file); // undefined
console.log(req.files); // undefined
console.log(req.body); // {}
} catch (err) {
next(err);
} finally {
req.connection.release();
}
});
Why is the req.body empty? Please help me understand what I'm doing wrong.