Reputation: 10673
In my Angularjs app I'm getting this issue (No 'Access-Control-Allow-Origin) when I try to make a GET request from YouTube.
...
myServices.factory('YouTubeService', function ($resource) {
return $resource('http://www.youtube.com/oembed?url=:url', {}, {
query: { method: 'GET', isArray: true },
})
});
...
called with:
YouTubeService.query({url: url}, function(response) {
alert(response)
})
I know it's to do with making a request from a different domain but I've no idea how to get around it. There are loads of questions already on this but I can't get anything from any of them.
I have tried this in my config block:
delete $httpProvider.defaults.headers.common['X-Requested-With'];
but this doesn't do anything!
Upvotes: 0
Views: 282
Reputation: 7101
The problem is the service you are trying to call does not allow requests from your host. (I.E. does not that a "Access-Control-Allow-Origin: *" header). The easiest was to go about this is to develop a rest server that will accept the request and then send it to the service you wish to call. The following headers must be present in your restserver for it to work properly
Access-Control-Allow-Origin: * (To accept request from any domain) Access-Control-Allow-Headers: Content-Type (to allow the content-type header) Access-Control-Allow-Credentials: true (to accept cookie and other credentials)
If you are developing the restserver in PHP, you should add the headers on the construct function of the restserver class or on the beginning of the method function (eg public function post())
This is how to add an header in php
`header('Access-Control-Allow-Origin: *');`
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Credentials: true');
You might want to add an OPTIONS method too
Upvotes: 0
Reputation: 2996
In my opinion, one of the best ways to solve it is using a proxy – I use nginx
running on a machine and create a proxy for the API I want to access, and write custom header directives in nginx
to add the headers to the response from the proxy before sending it to the frontend.
Something like;
location /APIProxy {
resolver 8.8.8.8; # or the DNS of your choice
proxy_pass http://<original_api_url>;
proxy_http_version 1.1;
add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
}
For more, refer to this.
Upvotes: 1