Search code examples
javascriptajaxhttpcorshttp-status-code-405

Response to preflight request doesn't pass access control check - No 'Access-Control-Allow-Origin' header


I'm getting this error using ngResource to call a REST API on Amazon Web Services:

XMLHttpRequest cannot load http://server.apiurl.com:8000/s/login?login=facebook. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. Error 405

Service:

socialMarkt.factory('loginService', ['$resource', function ($resource) {
    var apiAddress = "http://server.apiurl.com:8000/s/login/";
    return $resource(apiAddress, {
        login: "facebook",
        access_token: "@access_token",
        facebook_id: "@facebook_id"
    }, {
        getUser: {
            method: 'POST'
        }
    });
}]);

Controller:

[...]
loginService.getUser(JSON.stringify(fbObj)),
    function (data) {
        console.log(data);
    },
    function (result) {
        console.error('Error', result.status);
    }
[...]

I'm using Chrome. What else can I do in order to fix this problem?

I've even configured the server to accept headers from origin localhost.


Solution

  • You are running into CORS issues.

    There are several ways to fix or workaround this.

    1. Turn off CORS. For example: How to turn off CORS in Chrome
    2. Use a plugin for your browser
    3. Use a proxy, such as nginx. Example of how to set up
    4. Go through the necessary setup for your server. This is more a factor of the web server you have loaded on your EC2 instance (presuming this is what you mean by "Amazon web service"). For your specific server, you can refer to the enable CORS website.

    More verbosely, you are trying to access api.serverurl.com from localhost. This is the exact definition of a cross-domain request.

    By either turning it off just to get your work done (OK, but poor security for you if you visit other sites and just kicks the can down the road) or you can use a proxy which makes your browser think all requests come from the local host when really you have a local server that then calls the remote server.

    So api.serverurl.com might become localhost:8000/api, and your local nginx or other proxy will send to the correct destination.


    Now by popular demand, 100% more CORS information—the same great taste!


    Bypassing CORS is exactly what is shown for those simply learning the front end. HTTP Example with Promises