axios - send form data AND non-form data

孤人 提交于 2020-07-15 09:07:07

问题


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:


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



来源:https://stackoverflow.com/questions/52919934/axios-send-form-data-and-non-form-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!