且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AngularJS $http.post() 触发 get 请求而不是 post

更新时间:2021-07-12 23:56:31

似乎这个问题很老而且没有答案,但 google 把我带到了这里.我希望有人会觉得这个答案有用.

Seems the question is old and unanswered but google led me here. I hope someone will find this answer useful.

我遇到了同样的问题.$http 设置为 POST 但服务器从 GET 请求返回错误.

I had the same problem. $http was set to POST but server was returning error from GET request.

在网络检查器中检查标题后,它显示浏览器实际上做了两个请求:

After checking the headers in a web inspector it shows the browser actually did two requests:

update/ 301     text/html   angular.js:11442        
update  405     xhr         https://test.site/post/update

第一个是来自 $http 的,第二个是重定向之后的.如您所见,尾随斜杠 URL 被重定向到非尾随 URL.通过此重定向,POST 请求也将更改为 GET.

The first one is the one from $http and the second one is after a redirect. As you can see the trailing slash URL is redirected to a non trailing one. With this redirect a POST request gets also changed to GET as well.

解决方案是将您的请求 url 更改为不包含尾部斜杠:

The solution is to change your request url to not contain trailing slashes:

url: BASE_URL+"/leads/update",