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, typescript和form-data(v4.0.0)工作:
import FormData from "form-data";
import axios from "axios";
async function login() {
var data = new FormData();
data.append("User", "asdf");
const return = await axios.post(
"https://ptsv2.com/t/1q9gx-1652805776/post", data,
{ headers: data.getHeaders() }
);
console.log(return);
}
上传(多个)二进制文件
node . js
当您想通过多部分/form-data发布文件时,事情就变得复杂了,尤其是多个二进制文件。下面是一个工作示例:
const FormData = require('form-data')
const fs = require('fs')
const path = require('path')
const formData = new FormData()
formData.append('files[]', JSON.stringify({ to: [{ phoneNumber: process.env.RINGCENTRAL_RECEIVER }] }), 'test.json')
formData.append('files[]', fs.createReadStream(path.join(__dirname, 'test.png')), 'test.png')
await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData, {
headers: formData.getHeaders()
})
而不是头:{'Content-Type': 'multipart/form-data'}我更喜欢头:formData.getHeaders()
我在上面使用了async和await,如果你不喜欢它们,你可以将它们更改为简单的Promise语句
为了添加你自己的头文件,你只需要头文件:{…formData.getHeaders()}
新增内容如下:
浏览器
浏览器的FormData不同于NPM包form-data。以下代码在浏览器中为我工作:
HTML:
<input type="file" id="image" accept="image/png"/>
JavaScript:
const formData = new FormData()
// add a non-binary file
formData.append('files[]', new Blob(['{"hello": "world"}'], { type: 'application/json' }), 'request.json')
// add a binary file
const element = document.getElementById('image')
const file = element.files[0]
formData.append('files[]', file, file.name)
await rc.post('/restapi/v1.0/account/~/extension/~/fax', formData)
在我的情况下,我必须像下面这样添加边界头:
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,这个解决方案也很有用。
当需要从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));
我在使用带有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);
});