Reputation: 17042
I am having an $http request in my localhost which is calling a url of some api. I am getting an error on executing the call
Response for preflight has invalid HTTP status code 403
Can I do anything using angular so that I can fix this issue? I have CROS plugin of chrome to allow cross origin request
$http({
method: 'POST',
url: url,
data:data1,
headers: {
'Access-Control-Allow-Origin': '*',
}
})
Upvotes: 1
Views: 16303
Reputation: 2194
I have this code in angularjs:
$http.post('http://localhost:8080/employee/'
, $scope.alumno
,{headers: {'Content-Type': 'application/json'}}
).success(function(data){
if ( data.err === false ) {
$scope.actualizado = true;
setTimeout(function() {
$scope.actualizado = false;
$scope.$apply();
}, 3500);
};
});
My API have this data:
//Add employee:
Url: http://localhost:8080/employee
Type request: POST
Add a new employee:
{
"firstName": "Javier",
"lastName": "Piedra",
}`
I use chrone with extension for available CORS for the GET all perfect but post sample this error:
XMLHttpRequest cannot load http://localhost:8080/employee/. Response for
preflight has invalid HTTP status code 403
In my app.config use:
app.config( function($routeProvider,$httpProvider){
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
Maybe this can be a solution for your issue.
Regards
Upvotes: 1
Reputation: 299
If you using java restful controller as your server. You can refer to https://spring.io/guides/gs/rest-service-cors/
I added @CrossOrigin(origins = "*") on my controller and it works. Basically, you cannot do anything in the client side.
Lin
Upvotes: 5
Reputation: 2679
Ok so here's how I figured this out. It all has to do with CORS policy. Before the POST request, Chrome was doing a preflight OPTIONS request, which should be handled and acknowledged by the server prior to the actual request. Now this is really not what I wanted for such a simple server. Hence, resetting the headers client side prevents the preflight:
app.config(function ($httpProvider) {
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
});
The browser will now send a POST directly. Hope this helps a lot of folks out there... My real problem was not understanding CORS enough.
Link to a great explanation: http://www.html5rocks.com/en/tutorials/cors/
Kudos to this answer for showing me the way. AngularJS POST Fails: Response for preflight has invalid HTTP status code 404
Upvotes: 1