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中使用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);
  });

其他回答

我在使用带有axios的FormData对https://apps.dev.microsoft.com服务进行调用时遇到了类似的问题,它错误地显示出“请求体必须包含以下参数:'grant_type'”

重新格式化后的数据

{
  grant_type: 'client_credentials',
  id: '123',
  secret: '456789'
}

to

"grant_type=client_credentials&id=123&secret=456789"

下面的代码起作用了:

const config: AxiosRequestConfig = {
    method: 'post',
    url: https://apps.dev.microsoft.com/auth,
    data: 'grant_type=client_credentials&id=123&secret=456789',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
    }
};

axios(config)
.then(function (response) {
  console.log(JSON.stringify(response.data));
})
.catch(function (error) {
  console.log(error);
});

当需要从NodeJS环境中使用axios POST x-www-form- urlenencoded数据时,这应该工作得很好。您可能需要向配置中添加一个授权标头。如果端点需要身份验证,则返回头对象。

const config = {
  headers: {
    accept: 'application/json',
    'cache-control': 'no-cache',
    'content-type': 'application/x-www-form-urlencoded'
  }

const params = new URLSearchParams({key1: value1, key2: value2});

return axios
  .post(url, params.toString(), config)
  .then((response) => {
    return response.data;
  })
  .catch((error) => console.error(error));

在发送请求时设置边界(服务器用来解析有效负载)。在发出请求之前无法获得边界。因此,更好的方法是从你的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);
  });

在我的例子中,问题是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”的值并不重要,除非您有一些接收端处理需要它。

你可以通过使用FormData()来发布axios数据,比如:

var bodyFormData = new FormData();

然后将字段添加到您想要发送的表单:

bodyFormData.append('userName', 'Fred');

如果你正在上传图片,你可能想要使用.append

bodyFormData.append('image', imageFile); 

然后你可以使用axios post方法(你可以相应地修改它)

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

相关GitHub问题:

不能得到一个。post与'Content-Type': 'multipart/form-data'工作@ axios/axios