4

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.

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

1 Comment

I need to send a object. What should I do ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.