axios POST请求击中控制器上的url,但将空值设置为我的POJO类,当我在chrome中通过开发人员工具时,有效载荷包含数据。我做错了什么?

Axios POST请求

var body = {
    userName: 'Fred',
    userEmail: 'Flintstone@gmail.com'
}

axios({
    method: 'post',
    url: '/addUser',
    data: body
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

浏览器响应:

如果我设置头信息为:

headers:{
  Content-Type:'multipart/form-data'
}

请求抛出错误

在发布多部分/表单数据时出错。内容类型报头缺少边界

如果我在邮递员中提出相同的请求,它就会正常工作,并为我的POJO类设置值。

有人能解释如何设置边界或如何使用axios发送表单数据吗?


当前回答

在我的例子中,问题是FormData追加操作的格式需要额外的“options”参数填充来定义文件名:

var formData = new FormData();
formData.append(fieldName, fileBuffer, {filename: originalName});

我看到很多人抱怨axios有问题,但实际上根本原因是没有正确使用form-data。我的版本是:

"axios": "^0.21.1",
"form-data": "^3.0.0",

在接收端,我用multer处理这个,最初的问题是文件数组没有被填充-我总是得到一个没有从流解析文件的请求。

此外,有必要在axios请求中传递表单数据头集:

        const response = await axios.post(getBackendURL() + '/api/Documents/' + userId + '/createDocument', formData, {
        headers: formData.getHeaders()
    });

整个函数是这样的:

async function uploadDocumentTransaction(userId, fileBuffer, fieldName, originalName) {
    var formData = new FormData();
    formData.append(fieldName, fileBuffer, {filename: originalName});

    try {
        const response = await axios.post(
            getBackendURL() + '/api/Documents/' + userId + '/createDocument',
            formData,
            {
                headers: formData.getHeaders()
            }
        );

        return response;
    } catch (err) {
        // error handling
    }
}

“fieldName”的值并不重要,除非您有一些接收端处理需要它。

其他回答

检查querystring。

你可以这样使用它:

var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

在发送请求时设置边界(服务器用来解析有效负载)。在发出请求之前无法获得边界。因此,更好的方法是从你的FormData中使用getBoundary()。

var formData = new FormData();
formData.append('userName', 'Fred');
formData.append('file0', fileZero);
formData.append('file1', fileOne);

axios({
  method: "post",
  url: "myurl",
  data: formData,
  headers: {
      'Content-Type':  `multipart/form-data; ${formData.getBoundary()}`,
})
  .then(function (response) {
    //handle success
    console.log(response);
  })
  .catch(function (response) {
    //handle error
    console.log(response);
  });

在我的情况下,我必须像下面这样添加边界头:

const form = new FormData();
form.append(item.name, fs.createReadStream(pathToFile));

const response = await axios({
    method: 'post',
    url: 'http://www.yourserver.com/upload',
    data: form,
    headers: {
        'Content-Type': `multipart/form-data; boundary=${form._boundary}`,
    },
});

如果你正在使用React Native,这个解决方案也很有用。

更直接的是:

axios.post('/addUser',{
    userName: 'Fred',
    userEmail: 'Flintstone@gmail.com'
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

在我的例子中,问题是FormData追加操作的格式需要额外的“options”参数填充来定义文件名:

var formData = new FormData();
formData.append(fieldName, fileBuffer, {filename: originalName});

我看到很多人抱怨axios有问题,但实际上根本原因是没有正确使用form-data。我的版本是:

"axios": "^0.21.1",
"form-data": "^3.0.0",

在接收端,我用multer处理这个,最初的问题是文件数组没有被填充-我总是得到一个没有从流解析文件的请求。

此外,有必要在axios请求中传递表单数据头集:

        const response = await axios.post(getBackendURL() + '/api/Documents/' + userId + '/createDocument', formData, {
        headers: formData.getHeaders()
    });

整个函数是这样的:

async function uploadDocumentTransaction(userId, fileBuffer, fieldName, originalName) {
    var formData = new FormData();
    formData.append(fieldName, fileBuffer, {filename: originalName});

    try {
        const response = await axios.post(
            getBackendURL() + '/api/Documents/' + userId + '/createDocument',
            formData,
            {
                headers: formData.getHeaders()
            }
        );

        return response;
    } catch (err) {
        // error handling
    }
}

“fieldName”的值并不重要,除非您有一些接收端处理需要它。