Lucas_Santos
Lucas_Santos

Reputation: 4740

Cross Domain Request with AngularJS doesn't work

I need to do a Cross Domain Request using Angular, but I got the error

XMLHttpRequest cannot load http://machine_name_in_my_network:8082/GetAll. No

'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:53379' is therefore not allowed access. The response had HTTP status code 500.

I saw here a solution sample, but doesn't worked for me.

This is a request from my localhost to a machine in my network and should return a JSON.

Code Snippet

//Controller 
function crmContatosCtrl($scope, apiService) {
    apiService.get('/GetAll').then(function (data) {
       $scope.contatos = data;
    });

and then comes to my service

function comWebApi_Service($http, $log) {
    return {
        get: function (url, data) {

            //return $http.jsonp(ApiURL + url)
            //    .success(function (data) {
            //        debugger;
            //    })
            //    .error(function (data) {
            //        debugger;
            //    });

            return $http.get(ApiURL + url, data).then(
                function (res) {                
                    return res.data;
                });
        },

    angular
        .module('app')
        .config(['$httpProvider', function($httpProvider) {
            $httpProvider.defaults.useXDomain = true;
            delete $httpProvider.defaults.headers.common['X-Requested-With'];
        }])
        .service('apiService', comWebApi_Service);

Upvotes: 1

Views: 456

Answers (2)

harishr
harishr

Reputation: 18055

you need to enable cors on server

e.g. to init it globally

    var cors = new EnableCorsAttribute("*", "*", "*");
    config.EnableCors(cors);

read more about it here... read section Scope Rules for [EnableCors]

Upvotes: 1

Peter Lyons
Peter Lyons

Reputation: 146034

This is missing code on the server side, not in your browser AngularJS code. You do not need either of these lines with recent angularjs builds. These are both based on outdated information (They won't break anything, they are just unnecessary and based on outdated copypasta):

$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];

Your server code needs to add the necessary CORS headers to its HTTP responses, so ask the maintainer to do so or post server side snippets and we can help with that.

Upvotes: 1

Related Questions