69
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!

Daniel Higueras
  • 2,289
  • 20
  • 33
Ru11
  • 839
  • 2
  • 9
  • 13

12 Answers12

26

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

  • this is by far the easiest answer for this question! thanks – Yar Sep 16 '15 at 20:13
  • this only works when you are developing, when you get your code to a server the code is going to appear again. Unless you are developing using ionic or phonegap which does this check using config.xml you will still need to set the headers on your angularjs code. – Magus Dec 04 '15 at 04:46
  • 9
    This is only a workaround, not a solution. It will work with development but once the code is deployed this issue has to be fixed. We cant expect every person using he website to have this plugin – Vatsal Jan 13 '16 at 07:03
  • 3
    True, but the "No Access-Control-Allow-Origin" problem is supposed to happen mainly when you are developing from a local environment, and you are requesting a server outside of your network (https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS). When you move your application to production you shouldn't have this problem. If your application runs from a different domain than your servers, you should configure your servers to allow CORS requests. – Patricio Córdova Feb 10 '16 at 20:36
  • @PatricioCórdova, I am new and have been developing my very first angular app with http. Currently I have both server and client running on my local host. server is on port 8080 and the client is on port 3000. I get the issue which is being discussed here. BTW, my question is, once I put my client and server into servers, will I be still getting the issue? I asking since u have mentioned that, this happens when we are developing in a local envionment. – vigamage Dec 25 '16 at 11:10
  • Hi @vigamage. Check this question: http://stackoverflow.com/questions/19966707/cors-error-on-same-domain. If you have a different port, the app is going to understand it as a different domain so you would still have the CORS issue. What you can do is to try to serve both requests under the same port, or set the client to allow CORS. I suppose you are using ExpressJS? Here is how: http://enable-cors.org/server_expressjs.html – Patricio Córdova Jan 02 '17 at 20:18
  • thank you.. But what I wanted to know is what will happen when the client and the server is put on to the servers. They will be not host on the same server. – vigamage Jan 03 '17 at 03:21
  • This is not a solution for the issue of the question, but definitely helps a lot when working behind a restrictive firewall – Yumarx Polanco Nov 10 '17 at 14:04
18

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.

ALi Mir
  • 181
  • 1
  • 4
15

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.

Lee Willis
  • 1,477
  • 9
  • 14
4

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!"}
Nadimul De Cj
  • 494
  • 4
  • 15
2

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.

1

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.

0

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.

Wtower
  • 15,424
  • 11
  • 94
  • 69
Thomas David Kehoe
  • 7,232
  • 7
  • 44
  • 73
0

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

0

Replace get with jsonp:

 $http.jsonp('http://mywebservice').success(function ( data ) {
    alert(data);
    });
}
Travis Heeter
  • 9,968
  • 10
  • 69
  • 114
0

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")

-6

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

Disable same origin policy in Chrome

Community
  • 1
  • 1
  • 3
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have [sufficient reputation](http://stackoverflow.com/help/privileges/comment) you will be able to comment on any post. – Scott Solmer Sep 22 '14 at 21:34
  • Please take a look in this link: [Understanding AJAX CORS and security considerations](http://stackoverflow.com/questions/21854516/understanding-ajax-cors-and-security-considerations) – deividfortuna Mar 09 '17 at 11:20
-10

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.

  • @XelharK what do you mean by not sure if trolling? – Samuel Kwame Antwi Jun 05 '15 at 14:55
  • 4
    This solution will basically disable security checks in your browser for development purposes. As long as you're going to use the script on your own computer it's fine, but 99% of the time, this problem happens when someone is developing an application that requires some server request, and he's likely to release the application to the public at some point. This solution will just make it work ON YOUR MACHINE, it's a simple temporary bypass of the problem, not a solution at all. – XelharK Jun 07 '15 at 15:16
  • @XelharK that was the point i was trying to arrive at. You should create two copies of your chrome application. One is the secured app for browsing the web and the other one for testing. I hope that helps to clearify things – Samuel Kwame Antwi Jun 08 '15 at 15:55
  • 1
    Sure, that would make it work, but only on your machine. If that's all you need then I guess this works, but the problem is still not solved, this is only a temporary way around it. – XelharK Jun 09 '15 at 16:26
  • @XelharK yes only on your local machine for local development and testing. I realized after deploying to production, it worked with the normal browser with the security settings because at that point i am accessing the application out side my local network and secured network and the server is sending back all the required header information – Samuel Kwame Antwi Jun 11 '15 at 13:04