2019独角兽企业重金招聘Python工程师标准>>>
遇到这样一个问题,让我对http协议又有了深刻的理解。
springboot服务器端接受请求代码如下:
@RequestMapping(value = "/postuser/{id}", method = RequestMethod.POST)
public String postUserName(@RequestParam(value = "name") String username, @PathVariable String id)
{
return "say hello : " + username + " id: " + id;
}
请求js代码如下:
function changeEditorContent() {
//jquery请求
$.post('/postuser/123123', {
"name" : $scope.paperID,
"bbbbb" : "asdfasdf"
}, {}).success(function(data) {
console.log(data);
}).error(function(err) {
console.log(err);
});
//angularjs请求
$http.post('/postuser/123123', {
"name" : $scope.paperID,
"bbbbb" : "asdfasdf"
}, {}).success(function(data) {
console.log(data);
}).error(function(err) {
console.log(err);
});
}
前台的代码的差异在于,一个是angularjs提供的http请求方式,另一个是JQuery 提供的请求方式。
问题在于:用angularjs提供的http请求方式会报400错误,而JQuery则不报错。
搜了一圈发现有一篇文章给出了很好的解答:
http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/
核心的解释如下:
区别在于jQuery和AngularJS如何序列化和传输数据。 从根本上讲,问题在于您的服务器语言无法理解AngularJS的本机传输 - 这是一个耻辱,因为AngularJS肯定没有做错什么。 默认情况下,jQuery使用Content-Type:x-www-form-urlencoded和熟悉的foo = bar&baz = moe序列化来传输数据。 然而,AngularJS使用Content-Type:application / json和{“foo”:“bar”,“baz”:“moe”)JSON序列化传输数据,但是不幸的是,一些Web服务器语言(特别是PHP)不会原生排序。
angularJS请求的http头内容如下:
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, br
Accept-Language:zh-CN,zh;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:29
Content-Type:application/json;charset=UTF-8
Cookie:Idea-d52edc35=1123fe00-418e-4f63-88b1-a6ed52c3152f
Host:localhost:3333
Origin:https://localhost:3333
Pragma:no-cache
Referer:https://localhost:3333/
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
jQuery 请求的http头内容如下:
Accept:*/*
Accept-Encoding:gzip, deflate, br
Accept-Language:zh-CN,zh;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Content-Length:21
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Cookie:Idea-d52edc35=1123fe00-418e-4f63-88b1-a6ed52c3152f
Host:localhost:3333
Origin:https://localhost:3333
Pragma:no-cache
Referer:https://localhost:3333/
User-Agent:Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
X-Requested-With:XMLHttpRequest
重点注意Content-Type字段的不同导致springboot服务器端无法接受参数。