axios - 发送表单数据和非表单数据 [英] axios - send form data AND non-form data
问题描述
我正在使用 axios 将数据发送到我的 nodejs/express 服务器.如果我想发送表单数据,我会执行以下操作(并且工作正常):
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
});
同样,上面的代码工作正常.这是它要去的 /someRoute 端点:
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'):
});
但是我如何同时发送formDate 和date 数据?我尝试了以下(但不起作用):
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
});
和端点:
app.post('/someRoute', (req, res) => {
const uploadedFile = req.files.nameOfFile;
const date = req.body.date;
res.send('success'):
});
这给了我一个 500 ERROR.
推荐答案
你可以做你已经做的同样的事情,只需将你也想发送的其他数据附加到 formData..所以formData.append(‘date’, date);
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);
这篇关于axios - 发送表单数据和非表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!