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发送表单数据吗?
我需要一次使用axios上传许多文件,因为FormData API,我挣扎了一段时间:
// const instance = axios.create(config);
let fd = new FormData();
for (const img of images) { // images is an array of File Object
fd.append('images', img, img.name); // multiple upload
}
const response = await instance({
method: 'post',
url: '/upload/',
data: fd
})
我没有指定content-type: multipart/form-data头!
我在使用带有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);
});
在我的例子中,问题是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”的值并不重要,除非您有一些接收端处理需要它。
import axios from "axios";
import qs from "qs";
const url = "https://yourapplicationbaseurl/api/user/authenticate";
let data = {
Email: "testuser@gmail.com",
Password: "Admin@123"
};
let options = {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
data: qs.stringify(data),
url
};
axios(options)
.then(res => {
console.log("yeh we have", res.data);
})
.catch(er => {
console.log("no data sorry ", er);
});
};