Reputation: 2301
I'm using axios to send data to my nodejs/express server. If I want to send form data, I do the following (and it works fine):
const formData = new FormData();
formData.append('nameOfFile', the_file);
axios({
method: 'post',
url: '/someRoute',
data: formData
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
// Do something with response
}).catch(err => {
// Do something with err
});
Again, the above code works fine. Here is the /someRoute endpoint that it goes to:
app.post('/someRoute', (req, res) => {
const uploadedFile = req.files.nameOfFile;
res.send('success'):
});
The endpoint always successfully receives the file. So far, so good.
If I want to send some other piece of data, like a date, I can send it like so (and it also works):
const date = '2012-02-13';
axios({
method: 'post',
url: '/someRoute',
data: date
})
app.post('/someRoute', (req, res) => {
const date = req.body.date;
res.send('success'):
});
But how do I send both the formDate and date data? I tried the following (but it doesn't work):
const formData = new FormData();
formData.append('nameOfFile', the_file);
axios({
method: 'post',
url: '/someRoute',
data: {
form: formData,
date: '2012-02-13'
},
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
// Do something with response
}).catch(err => {
// Do something with err
});
And the endpoint:
app.post('/someRoute', (req, res) => {
const uploadedFile = req.files.nameOfFile;
const date = req.body.date;
res.send('success'):
});
This gives me a 500 ERROR.
Upvotes: 4
Views: 2463
Reputation: 716
You can do the same thing you already did, just append the other data you also want to send to formData.. So formData.append(‘date’, date);
Upvotes: 3