遇到这样一个问题,让我对http协议又有了深入的理解。jquery
springboot服务器端接受请求代码以下:angularjs
@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代码以下:ajax
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 提供的请求方式。spring
问题在于:用angularjs提供的http请求方式会报400错误,而JQuery则不报错。json
搜了一圈发现有一篇文章给出了很好的解答:springboot
http://victorblog.com/2012/12/20/make-angularjs-http-service-behave-like-jquery-ajax/服务器
核心的解释以下:app
区别在于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)不会原生排序。post
angularJS请求的http头内容以下:url
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服务器端没法接受参数。