AngularJS $ http.post()触发get请求而不是post [英] AngularJS $http.post() firing get request instead of post
问题描述
我在角度和laravel中构建一个API服务,当我向API发送GET调用时,Everythings工作正常,但是当我触发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';
实例化但是,我一直得到 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.
检查Web检查器中的标题后,它显示浏览器实际上发出了两个请求:
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.
解决方法是将您的请求网址更改为不包含尾部斜杠:
The solution is to change your request url to not contain trailing slashes:
url: BASE_URL+"/leads/update",
这篇关于AngularJS $ http.post()触发get请求而不是post的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!