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发送表单数据吗?
当需要从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 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头!
在我的情况下,我必须像下面这样添加边界头:
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,这个解决方案也很有用。
https://www.npmjs.com/package/axios
它的工作
// "content-type": "application/x-www-form-urlencoded",
//提交
import axios from 'axios';
let requestData = {
username : "abc@gmail.cm",
password: "123456"
};
const url = "Your Url Paste Here";
let options = {
method: "POST",
headers: {
'Content-type': 'application/json; charset=UTF-8',
Authorization: 'Bearer ' + "your token Paste Here",
},
data: JSON.stringify(requestData),
url
};
axios(options)
.then(response => {
console.log("K_____ res :- ", response);
console.log("K_____ res status:- ", response.status);
})
.catch(error => {
console.log("K_____ error :- ", error);
});
获取请求
fetch(url, {
method: 'POST',
body: JSON.stringify(requestPayload),
headers: {
'Content-type': 'application/json; charset=UTF-8',
Authorization: 'Bearer ' + token,
},
})
// .then((response) => response.json()) . // commit out this part if response body is empty
.then((json) => {
console.log("response :- ", json);
}).catch((error)=>{
console.log("Api call error ", error.message);
alert(error.message);
});