axios-发送表单数据和非表单数据 [英] axios - send form data AND non-form data

查看:386
本文介绍了axios-发送表单数据和非表单数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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 日期数据?我尝试了以下操作(但不起作用):

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错误.

推荐答案

您可以执行已经完成的相同操作,只需将要发送的其他数据附加到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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆