Angular $http.post提交application/json请求
$http.post概述
基本语法
$http.post(url, data, config)
.success(function(data,status,headers,config){
})
.error(function(data,status,headers,config){
})
说明
$http.post 默认是以application/x-www-form-urlencoded方式提交请求的,后端无法用实体类直接接受json参数,如果直接传的话后台会报错:
$http.post修改请求头
修改请求头配置的Content-Type属性,提交application/json请求
var url = jrzhCTX + "/bohai/request/test.json";
var userInfo = {"customerName": "dengheng", "certId": "621018887771122234", "phone": "119110112114"}
var data = {
"orderNo": "ORDER20201230160408",
"userInfo": userInfo
}
var postCfg = {
headers: {'Content-Type': 'application/json;charset=UTF-8'}
};
$http.post(url, JSON.stringify(data), postCfg)
.success(function(data,status,headers,config){
console.log(data)
if (data && data.status == "success") {
layer.alert("请求成功");
} else {
layer.alert("失败!" + data.msg);
}
}
).error(function(data,status,headers,config){
console.log(data)
layer.alert("请求异常!");
});
这里注意参数data需用JSON.stringify(data)
转成字符串。
后端直接实体类去接收json参数即可:
@RequestMapping(method = RequestMethod.POST, value = "test")
@ResponseBody
public ResultBean test(@RequestBody OrderReq req) {
logger.info("test() -- req =>> " + req.toString());
ResultBean result = new ResultBean();
result.setObjs(new Object[]{});
result.setStatus(ResultBean.SUCCCESS);
result.setMsg("ok");
return result;
}
后端控制台输出日志:
test() -- reqJson =>> { "orderNo": "", "userInfo": { "accountNo": "", "bankCode": "", "certId": "621018887771122234", "commAdd": "", "companyAddress": "", "companyName": "", "companyPhone": "", "customerName": "dengheng", "marriage": "", "phone": "119110112114", "realEstateType": "", "sex": "" } }