How to enable CORS in AngularJs How to enable CORS in AngularJs javascript javascript

How to enable CORS in AngularJs


You don't. The server you are making the request to has to implement CORS to grant JavaScript from your website access. Your JavaScript can't grant itself permission to access another website.


I had a similar problem and for me it boiled down to adding the following HTTP headers at the response of the receiving end:

Access-Control-Allow-Headers: Content-TypeAccess-Control-Allow-Methods: GET, POST, OPTIONSAccess-Control-Allow-Origin: *

You may prefer not to use the * at the end, but only the domainname of the host sending the data. Like *.example.com

But this is only feasible when you have access to the configuration of the server.


Try using the resource service to consume flickr jsonp:

var MyApp = angular.module('MyApp', ['ng', 'ngResource']);MyApp.factory('flickrPhotos', function ($resource) {    return $resource('http://api.flickr.com/services/feeds/photos_public.gne', { format: 'json', jsoncallback: 'JSON_CALLBACK' }, { 'load': { 'method': 'JSONP' } });});MyApp.directive('masonry', function ($parse) {    return {        restrict: 'AC',        link: function (scope, elem, attrs) {            elem.masonry({ itemSelector: '.masonry-item', columnWidth: $parse(attrs.masonry)(scope) });        }    };        });MyApp.directive('masonryItem', function () {    return {        restrict: 'AC',        link: function (scope, elem, attrs) {            elem.imagesLoaded(function () {               elem.parents('.masonry').masonry('reload');            });        }    };        });MyApp.controller('MasonryCtrl', function ($scope, flickrPhotos) {    $scope.photos = flickrPhotos.load({ tags: 'dogs' });});

Template:

<div class="masonry: 240;" ng-controller="MasonryCtrl">    <div class="masonry-item" ng-repeat="item in photos.items">        <img ng-src="{{ item.media.m }}" />    </div></div>