I'm trying to send a post request with front-end javascript fetch, a form object, and body-parser in an express app.
I can send the data as JSON, but when I try to use a form-object the request body is blank. Could someone please tell me what I am doing wrong?
app.js
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
Here is my route:
exports.post_endpoint = async(req, res)=>{
console.log('req.body = ', req.body);
res.send({
test: 'test'
});
};
If I define the data without a form it works:
fetch(url, {
method: 'post',
headers: {'Content-Type': 'application/json', 'X-CSRF-TOKEN':"MY-CSRF-TOKEN"},
body: JSON.stringify({ "user": {
"email" : 'test1',
"password" : 'test2'
}}),
})
console output: req.body = { user: { email: 'test1', password: 'test2' } }
But when I try to use a form req.body is blank:
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');
fetch(url, {
method: 'post',
headers: {
"Content-Type": "multipart/form-data"
,'X-CSRF-TOKEN':"MY-CSRF-TOKEN"
},
body: formData
})
console output: req.body = {}
Edit:
Thanks to Quentin the answer was to add upload.none()
to the route and remove "Content-Type": "multipart/form-data"
from headers since fetch added that automatically.
in app.js:
const multer = require('multer');
const upload = multer({ dest: path.join(__dirname, 'uploads') });
app.post('/endpoint', upload.none(), my_router.post_endpoint);
multer upload.none()
sends the data to req.body
CodePudding user response:
You have two problems.
FormData
objects sendmultipart/form-data
payloads. You only have body parsing middleware for JSON payloads and URL encoded payloads.- The
Content-Type
formultipart/form-data
has a mandatoryboundary
parameter which you are omitting (also you have no way to find out what it is so you shouldn't override theContent-Type
header thatfetch
would otherwise automatically generate from theFormData
object)
The key benefit of FormData
is that it supports file attachments. Since you don't have any it ends up bloating your payload size. I'd stick to JSON or use URL Encoding.