AngularJS $http.post() 触发 get 请求而不是 post [英] AngularJS $http.post() firing get request instead of post
问题描述
我在 angular 和 laravel 中构建 API 服务,当我向 API 发出 GET 调用时一切正常,但是当我发出 POST 调用时,该服务仍然使用 GET 方法而不是 POST.这就是我的服务:
i building an API service in angular and laravel, when i firing a GET call to the API everythings work fine, but when i fire POST call the service still use GET method instead of POST. that is my service:
function LeadsAPI($http,$q,BASE_URL)
{
this.updateLead = function (lead_data) {
var url = BASE_URL+"/leads/update/";
var deferred = $q.defer();
$http.post(url , lead_data).then(function(response){
deferred.resolve(response.data);
});
return deferred.promise;
}
}
我从控制器调用这个函数:
i call to this function from a Controller:
LeadsController.$inject = ['$scope', 'LeadsAPI'];
function LeadsController($scope , LeadsAPI)
{
LeadsAPI.updateLead({'lead_id' : res._id, 'the_lead': {'fist_name' : 'asd asd'}}).then(function (res) {
console.log(res);
});
}
我尝试将参数作为字符串传递(a=b&c=d...")并添加标题:
i tried pass the parameters as a string ("a=b&c=d...") and added header :
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
在我的应用程序模块实例化的 run
函数中,但我不断收到 405(不允许的方法)
错误.任何想法为什么以及如何解决它?非常感谢大家!:)
in the run
function at my App module instantiation but yet, i keep getting 405 (Method Not Allowed)
error.
any ideas why and how to solve it? thank you very much all! :)
推荐答案
似乎这个问题很老而且没有答案,但 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",
这篇关于AngularJS $http.post() 触发 get 请求而不是 post的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!