[javascript] Origin is not allowed by Access-Control-Allow-Origin

I'm making an Ajax.request to a remote PHP server in a Sencha Touch 2 application (wrapped in PhoneGap).

The response from the server is the following:

XMLHttpRequest cannot load http://nqatalog.negroesquisso.pt/login.php. Origin http://localhost:8888 is not allowed by Access-Control-Allow-Origin.

How can I fix this problem?

This question is related to javascript ajax cors xmlhttprequest cross-domain

The answer is


In Ruby on Rails, you can do in a controller:

headers['Access-Control-Allow-Origin'] = '*'

I will give you a simple solution for this one. In my case I don't have access to a server. In that case you can change the security policy in your Google Chrome browser to allow Access-Control-Allow-Origin. This is very simple:

  1. Create a Chrome browser shortcut
  2. Right click short cut icon -> Properties -> Shortcut -> Target

Simple paste in "C:\Program Files\Google\Chrome\Application\chrome.exe" --allow-file-access-from-files --disable-web-security.

The location may differ. Now open Chrome by clicking on that shortcut.


If you're writing a Chrome Extension and get this error, then be sure you have added the API's base URL to your manifest.json's permissions block, example:

"permissions": [
    "https://itunes.apple.com/"
]

If you have an ASP.NET / ASP.NET MVC application, you can include this header via the Web.config file:

<system.webServer>
  ...

    <httpProtocol>
        <customHeaders>
            <!-- Enable Cross Domain AJAX calls -->
            <remove name="Access-Control-Allow-Origin" />
            <add name="Access-Control-Allow-Origin" value="*" />
        </customHeaders>
    </httpProtocol>
</system.webServer>

This was the first question/answer that popped up for me when trying to solve the same problem using ASP.NET MVC as the source of my data. I realize this doesn't solve the PHP question, but it is related enough to be valuable.

I am using ASP.NET MVC. The blog post from Greg Brant worked for me. Ultimately, you create an attribute, [HttpHeaderAttribute("Access-Control-Allow-Origin", "*")], that you are able to add to controller actions.

For example:

public class HttpHeaderAttribute : ActionFilterAttribute
{
    public string Name { get; set; }
    public string Value { get; set; }
    public HttpHeaderAttribute(string name, string value)
    {
        Name = name;
        Value = value;
    }

    public override void OnResultExecuted(ResultExecutedContext filterContext)
    {
        filterContext.HttpContext.Response.AppendHeader(Name, Value);
        base.OnResultExecuted(filterContext);
    }
}

And then using it with:

[HttpHeaderAttribute("Access-Control-Allow-Origin", "*")]
public ActionResult MyVeryAvailableAction(string id)
{
    return Json( "Some public result" );
}

You may make it work without modifiying the server by making the broswer including the header Access-Control-Allow-Origin: * in the HTTP OPTIONS' responses.

In Chrome, use this extension. If you are on Mozilla check this answer.


This might be handy for anyone who needs to an exception for both 'www' and 'non-www' versions of a referrer:

 $referrer = $_SERVER['HTTP_REFERER'];
 $parts = parse_url($referrer);
 $domain = $parts['host'];

 if($domain == 'google.com')
 {
         header('Access-Control-Allow-Origin: http://google.com');
 }
 else if($domain == 'www.google.com')
 {
         header('Access-Control-Allow-Origin: http://www.google.com');
 }

If you get this in Angular.js, then make sure you escape your port number like this:

var Project = $resource(
    'http://localhost\\:5648/api/...', {'a':'b'}, {
        update: { method: 'PUT' }
    }
);

See here for more info on it.


In Ruby Sinatra

response['Access-Control-Allow-Origin'] = '*' 

for everyone or

response['Access-Control-Allow-Origin'] = 'http://yourdomain.name' 

When you receive the request you can

var origin = (req.headers.origin || "*");

than when you have to response go with something like that:

res.writeHead(
    206,
    {
        'Access-Control-Allow-Credentials': true,
        'Access-Control-Allow-Origin': origin,
    }
);

If you don't have control of the server, you can simply add this argument to your Chrome launcher: --disable-web-security.

Note that I wouldn't use this for normal "web surfing". For reference, see this post: Disable same origin policy in Chrome.

One you use Phonegap to actually build the application and load it onto the device, this won't be an issue.


We also have same problem with phonegap application tested in chrome. One windows machine we use below batch file everyday before Opening Chrome. Remember before running this you need to clean all instance of chrome from task manager or you can select chrome to not to run in background.

BATCH: (use cmd)

cd D:\Program Files (x86)\Google\Chrome\Application\chrome.exe --disable-web-security

if you're under apache, just add an .htaccess file to your directory with this content:

Header set Access-Control-Allow-Origin: *

Header set Access-Control-Allow-Headers: content-type

Header set Access-Control-Allow-Methods: *

If you're using Apache just add:

<ifModule mod_headers.c>
    Header set Access-Control-Allow-Origin: *
</ifModule>

in your configuration. This will cause all responses from your webserver to be accessible from any other site on the internet. If you intend to only allow services on your host to be used by a specific server you can replace the * with the URL of the originating server:

Header set Access-Control-Allow-Origin: http://my.origin.host

I've run into this a few times when working with various APIs. Often a quick fix is to add "&callback=?" to the end of a string. Sometimes the ampersand has to be a character code, and sometimes a "?": "?callback=?" (see Forecast.io API Usage with jQuery)


This is because of same-origin policy. See more at Mozilla Developer Network or Wikipedia.

Basically, in your example, you need load the http://nqatalog.negroesquisso.pt/login.php page only from nqatalog.negroesquisso.pt, not localhost.


As Matt Mombrea is correct for the server side, you might run into another problem which is whitelisting rejection.

You have to configure your phonegap.plist. (I am using a old version of phonegap)

For cordova, there might be some changes in the naming and directory. But the steps should be mostly the same.

First select Supporting files > PhoneGap.plist

enter image description here

then under "ExternalHosts"

Add a entry, with a value of perhaps "http://nqatalog.negroesquisso.pt" I am using * for debugging purposes only.

enter image description here


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to cors

Axios having CORS issue Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource How to allow CORS in react.js? Set cookies for cross origin requests XMLHttpRequest blocked by CORS Policy How to enable CORS in ASP.net Core WebAPI No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API How to overcome the CORS issue in ReactJS Trying to use fetch and pass in mode: no-cors

Examples related to xmlhttprequest

What is difference between Axios and Fetch? Basic Authentication Using JavaScript XMLHttpRequest module not defined/found loading json data from local file into React JS AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource Edit and replay XHR chrome/firefox etc? AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https jQuery has deprecated synchronous XMLHTTPRequest Keep getting No 'Access-Control-Allow-Origin' error with XMLHttpRequest Sending a JSON to server and retrieving a JSON in return, without JQuery

Examples related to cross-domain

How to enable CORS in ASP.net Core WebAPI How to create cross-domain request? What are the integrity and crossorigin attributes? jQuery ajax request being block because Cross-Origin How to switch to another domain and get-aduser POST request not allowed - 405 Not Allowed - nginx, even with headers included Firefox 'Cross-Origin Request Blocked' despite headers No 'Access-Control-Allow-Origin' header is present on the requested resource- AngularJS Ajax Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?