后台定义需要formData格式的数据:即通过表单提交post请求传送的数据
前端用ajax的post请求传送的数据后台无法接收(后台接收的数据对象为空):
错误代码如下:
//买卖EMT操作
operateEMTF(operate){
let _this = this;
let api = "order/place";
let temp = {
type:“buy-limit”,
price:0.8763,
quantity:1000
};
console.log(temp);
_this.axios.post(api,{
type:temp.type,
price:temp.price.toString(),
quantity:temp.quantity.toString()
}).then(res=>{
// console.log(temp,res);
_this.buy.price = "";
_this.buy.quantity = "";
_this.sell.price = "";
_this.sell.quantity = "";
});
},
解决方案一:前端解决
必须把参数temp的json格式转化为formData格式:
代码如下:
//买卖EMT操作
operateEMTF(operate){
let _this = this;
let api = "order/place";
let temp = {};
if(operate=="buy"){
temp = _this.buy;
}else{
temp = _this.sell;
}
console.log(temp);
//1.json格式转化formData格式
let fd = new FormData();
Object.keys(temp).forEach(key => fd.append(key, temp[key]))
_this.axios({
method: 'post',
url: api,
data: fd,
//2.在请求头中制定参数格式为formData格式
config: { headers: {'Content-Type': 'multipart/form-data' }}
})
.then(function (response) {
console.log(response);
})
.catch(function (response) {
console.log(response);
});
//2.或者简写如下:
_this.axios.post(api,fd,{
headers: {'Content-Type': 'multipart/form-data' }
}).then(res=>{
console.log(res);
});
},
解决方案二:后台解决
后台把request.body用json.loads转一下
post发送json与表单的post请求--后台无法接收到数据
最新推荐文章于 2023-05-06 09:52:18 发布