Thursday, 4 August 2016

javascript - I get "No 'Access-Control-Allow-Origin' header error " even though I set it





I am having this error even though I have headers assigned in angular's $http service:



function Hello($scope, $http) {
$http({
method: 'GET',
url: 'http://localhost:8080/races',

headers: {
'Access-Control-Allow-Headers': 'accept',
'Access-Control-Allow-Methods': 'GET',
'Access-Control-Allow-Origin': '*'
},
}).then(function successCallback(response) {
$scope.races = response;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.

});


}



This is full error message on console:



XMLHttpRequest cannot load http://localhost:8080/races. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63343' is therefore not allowed access. The response had HTTP status code 403.



HTML:






Hello AngularJS







The ID is {{races.raceId}}


The name is {{races.raceName}}







When I open the localhost:8080/races I can fully see the json:




[{"raceId":8446,"raceName":"test1"},{"raceId":8447,"raceName":"test2"}]

Answer



Your problem is related with the fact that 'Access-Control-Allow-Origin': '*' needs to be set at the server. By doing this you enable CORS (Cross-Origin Resource Sharing)



Browsers have a security policy that prevents your javascript code to make requests from services that are not within your domain. For example if your javascript code is executed in http://example.com and the service you are targeting is found at http://example.com/api/myservice then your request will go through normally. If however, the service you are trying to access is at http://someotherdomain.net then the browser will not complete your request successfully even if the server responds normally.



You will have to read documentation about whatever web server software you're using on how to set headers on it. When you set 'Access-Control-Allow-Origin': '*' on your server your are essentially saying to the world - "You can load my data onto any browser application that lives in any domain". This means anyone in the world can call your service and if you wish to prevent this, you will have to implement authentication (common for this are API key models).


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...