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

AngularjsAjaxCorsCross Domain

Angularjs Problem Overview


XMLHttpRequest cannot load http://mywebservice. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.

I get this error when I try to run my web-service from inside my code. I tried finding about it and tried many solutions which were suggested which I found on net. Pasting the code below.

<form name="LoginForm" ng-controller="LoginCtrl" ng-submit="init(username,password,country)">
    <label>Country</label><input type="text" ng-model="country"/><br/><br/>
	<label>UserName</label><input type="text" ng-model="username" /></br></br>
	<label>Password</label><input type="password" ng-model="password">
	</br>
	<button type="submit" >Login</button>
</form>

And controller form the corresponding js is:

app.controller('LoginController', ['$http', '$scope', function ($scope, $http) {
	$scope.login = function (credentials) {
	$http.get('http://mywebservice').success(function ( data ) {
		alert(data);
		});
	}
}]);

The web-service works fine when I hit it from URL bar. How to resolve the problem? Kindly help!

Angularjs Solutions


Solution 1 - Angularjs

The Chrome Webstore has an extension that adds the 'Access-Control-Allow-Origin' header for you when there is an asynchronous call in the page that tries to access a different host than yours.

The name of the extension is: "**Allow-Control-Allow-Origin: ***" and this is the link: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

Solution 2 - Angularjs

On the client side you can enable cors requests in AngularJS via

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

However if this still returns an error, this would imply that the server that you are making the request has to allow CORS request and has to be configured for that.

Solution 3 - Angularjs

This is a CORS issue. There are some settings you can change in angular - these are the ones I typically set in the Angular .config method (not all are related to CORS):

$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.defaults.headers.common["Accept"] = "application/json";
$httpProvider.defaults.headers.common["Content-Type"] = "application/json";

You also need to configure your webservice - the details of this will depend on the server side language you are using. If you use a network monitoring tool you will see it sends an OPTIONS request initially. Your server needs to respond appropriately to allow the CORS request.

The reason it works in your brower is because it isn't make a cross-origin request - whereas your Angular code is.

Solution 4 - Angularjs

I have a solution below and its works for me:

app.controller('LoginController', ['$http', '$scope', function ($scope, $http) {
$scope.login = function (credentials) {
$http({
        method: 'jsonp',
        url: 'http://mywebservice',
        params: {
            format: 'jsonp',
            callback: 'JSON_CALLBACK'
        }
    }).then(function (response) {
        alert(response.data);
    });
  }
}]);

in 'http://mywebservice'; there must be need a callback parameter which return JSON_CALLBACK with data.
There is a sample example below which works perfect

$scope.url = "https://angularjs.org/greet.php";
    $http({
        method: 'jsonp',
        url: $scope.url,
        params: {
            format: 'jsonp',
            name: 'Super Hero',
            callback: 'JSON_CALLBACK'
        }
    }).then(function (response) {
        alert(response.data);
    });

example output:

{"name":"Super Hero","salutation":"Apa khabar","greeting":"Apa khabar Super Hero!"}

Solution 5 - Angularjs

I added this and it worked fine for me.

web.api

config.EnableCors();

Then you will call the model using cors:

In a controller you will add at the top for global scope or on each class. It's up to you.

 [EnableCorsAttribute("http://localhost:51003/", "*", "*")]

Also, when your pushing this data to Angular it wants to see the .cshtml file being called as well, or it will push the data but not populate your view.

(function () {
    "use strict";
    angular.module('common.services',
	    ['ngResource'])
    .constant('appSettings',
    {
        serverPath: "http://localhost:51003/About"
    });
}());

//Replace URL with the appropriate path from production server.

I hope this helps anyone out, it took me a while to understand Entity Framework, and why CORS is so useful.

Solution 6 - Angularjs

In my case, I was trying to hit a WebAPI service on localhost from inside an MVC app that used a lot of Angular code. My WebAPI service worked fine with Fiddler via http://localhost/myservice. Once I took a moment to configure the MVC app to use IIS instead of IIS Express (a part of Visual Studio), it worked fine, without adding any CORS-related configuration to either area.

Solution 7 - Angularjs

I got

> No 'Access-Control-Allow-Origin' header is present

and the problem was with the URL I was providing. I was providing the URL without a route, e.g., https://misty-valley-1234.herokuapp.com/.

When I added a path it worked, e.g., https://misty-valley-1234.herokuapp.com/messages. With GET requests it worked either way but with POST responses it only worked with the added path.

Solution 8 - Angularjs

Use this extension for chrome. Allows to you request any site with ajax from any source. Adds to response 'Allow-Control-Allow-Origin: *' header

https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi/related

Solution 9 - Angularjs

Replace get with jsonp:

 $http.jsonp('http://mywebservice').success(function ( data ) {
    alert(data);
    });
}

Solution 10 - Angularjs

It is a problem on the server side. You have to add your client address to your server exposed API. If you are using Spring frame work you can annotate @CrossOrgin from org.springframework.web.bind.annotation.CrossOrigin;

Eg : @CrossOrigin(origins = "http://localhost:8080";)

Solution 11 - Angularjs

If you are using chrome: try open chrome with the args to disable web security like you see here:

https://stackoverflow.com/questions/3102819/disable-same-origin-policy-in-chrome

Solution 12 - Angularjs

This is how it worked for me. For Windows users testing with Bracket and AngularJS

  1. Go to your desktop

  2. Right click on your desktop and look for "NEW" in the popup drop down dialog box and it will expand

  3. Choose Shortcut

  4. A dialog box will open

  5. Click on Browse and look for Google Chrome.

  6. Click Ok->Next->Finish and it will create the google shortcut on your desktop

  7. Now Right Click on the Google Chrome icon you just created

  8. Click properties

  9. Enter this in the target path

    "C:\Program Files\Google\Chrome\Application\chrome.exe" --args --disable-web-security

  10. Save it

  11. Double click on your newly created chrome shortcut and past your link in the address bar and it will work.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRu11View Question on Stackoverflow
Solution 1 - AngularjsPatricio CórdovaView Answer on Stackoverflow
Solution 2 - AngularjsALi MirView Answer on Stackoverflow
Solution 3 - AngularjsLee WillisView Answer on Stackoverflow
Solution 4 - AngularjsNadimul De CjView Answer on Stackoverflow
Solution 5 - AngularjsJohn AldrinView Answer on Stackoverflow
Solution 6 - Angularjsuser5373289View Answer on Stackoverflow
Solution 7 - AngularjsThomas David KehoeView Answer on Stackoverflow
Solution 8 - AngularjsAmaru HashView Answer on Stackoverflow
Solution 9 - AngularjsTravis HeeterView Answer on Stackoverflow
Solution 10 - Angularjsuser8033402View Answer on Stackoverflow
Solution 11 - AngularjsdeividfortunaView Answer on Stackoverflow
Solution 12 - AngularjsSamuel Kwame AntwiView Answer on Stackoverflow