[英]axios - send form data AND non-form data
I'm using axios to send data to my nodejs/express server.我正在使用 axios 将数据发送到我的 nodejs/express 服务器。 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:
这是它转到的/someRoute端点:
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):如果我想发送一些其他数据,比如date ,我可以这样发送(它也可以):
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?但是如何同时发送formDate和date数据? 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 .这给了我500 ERROR 。
你可以做你已经做过的同样的事情,只需将你也想发送的其他数据附加到 formData .. 所以 formData.append('date', date);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.