AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

Alessandro picture Alessandro · Apr 9, 2015 · Viewed 327.1k times · Source

I'm writting my webApp and I'm using AngularJS. In this app I have created a file called script.js and I report this code:

var modulo = angular.module('progetto', ['ngRoute']);

    // configure our routes
    modulo.config(function ($routeProvider, $httpProvider) {
        $routeProvider

            // route for the home page
            .when('/', {
                templateUrl: 'listaFilm.html',
                controller: 'listaController'
            })

            // route for the description page
            .when('/:phoneName', {
                templateUrl: 'description.html',
                controller: 'descriptionController'
            });


            $httpProvider.defaults.headers.common['Access-Control-Allow-Origin'] = '*';

    });


    modulo.controller('listaController', function ($scope, $http) {
        $http.get('https://api.getevents.co/event?&lat=41.904196&lng=12.465974').success(function (data) {
            $scope.names = data;
            }).
            error(function (data, status) {
                $scope.names = "Request failed";
            });
    });

With this code I call API following RESTful principles. When I run the code i have this problem:

XMLHttpRequest cannot load https://api.getevents.co No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8383' is therefore not allowed access.

Reading on the web I understood that I have a problem called CORS...I have tried several solutions proposed but I didn't resolve the problem.
How can I fix the problem?
What's the code that I must add for fix it?

Answer

Kristjan Liiva picture Kristjan Liiva · Apr 9, 2015

This is a server side issue. You don't need to add any headers in angular for cors. You need to add header on the server side:

Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *

First two answers here: How to enable CORS in AngularJs