Reputation: 1
I am new to angularJs, right now I want to use $http.put to update an Json file at a remote repository.
but everytime I try, I get the following error
XMLHttpRequest cannot load http://blabla&action=update.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'localhost:9080' is therefore not allowed access.
So it doesn't work. now I did my part of search on Stack and google. a lot of people are saying I should add headers. I don't know how to add headers correctly and I have no idea how to verify if the headers are correctly added.
Can someone help me? The following is my code.
$http.defaults.headers.post['Access-Control-Allow-Origin'] = '*';
$http.defaults.headers.post['Access-Control-Allow-Methods'] = 'GET, POST, DELETE, PUT';
$http.defaults.headers.post['Access-Control-Allow-Credential'] = 'true';
$scope.update = function(key,value){
$scope.myData[key] = value;
$http.put('http://blabla&action=update', $scope.myData)
.success(function (data, status) {
alert('success');
})
the code above is still giving me the same error, from my research online, the headers are suppose to solve this problem... but it didn't. I don't know what I did wrong. thanks guys!
Upvotes: 0
Views: 2185
Reputation: 2288
Your main issue is that the headers need to be set on the server. Your error:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'localhost:9080' is therefore not allowed access.
is the key to all of this.
You are requesting from localhost:9080 to somewhere like foo.com/api. That endpoint needs to return an Access-Control-Allow-Origin: localhost:9080
header to your application.
Upvotes: 0
Reputation: 4138
You can pass a config object to the $http.put
method like this:
$http({
method: 'PUT',
url: 'http://blabla&action=update',
data: $scope.myData,
headers: {
"Access-Control-Allow-Origin": "self",
<other headers here>
}
})
.success(function (data, status) {
alert('success');
});
And you can verify the headers with the request within developer tools if you use Chrome or IE and FireBug if you use Firefox. More info on Angular Docs.
Upvotes: 1