axios -发送表单数据和非表单数据

4

我正在使用axios向我的nodejs/express服务器发送数据。如果我想发送表单数据,我会执行以下操作(它可以正常工作):

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

以上代码正常工作。这里是它所连接的/someRoute端点:

app.post('/someRoute', (req, res) => {
    const uploadedFile = req.files.nameOfFile;
    res.send('success'):
});

这个终端点总是成功接收文件。到目前为止,一切顺利。

如果我想发送其他数据,比如一个日期,我可以这样发送(它也能正常工作):

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'):
});

但是我该如何同时发送 formDatedate 数据呢?我尝试了以下代码(但是它并不能正常工作):

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

以及终端点:

app.post('/someRoute', (req, res) => {
    const uploadedFile = req.files.nameOfFile;
    const date = req.body.date;
    res.send('success'):
});

这让我收到了一个500错误
1个回答

3
你可以采用相同的方法,只需将你想要发送的其他数据附加到formData中即可。因此, formData.append('date', date);

1
我需要发送一个对象。我该怎么做? - gamer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接