[javascript] Firefox 'Cross-Origin Request Blocked' despite headers

I'm trying to make a simple cross-origin request, and Firefox is consistently blocking it with this error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at [url]. This can be fixed by moving the resource to the same domain or enabling CORS. [url]

It works fine in Chrome and Safari.

As far as I can tell I've set all the correct headers on my PHP to allow this to work. Here's what my server is responding with

HTTP/1.1 200 OK
Date: Mon, 23 Jun 2014 17:15:20 GMT
Server: Apache/2.2.22 (Debian)
X-Powered-By: PHP/5.4.4-14+deb7u8
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type
Access-Control-Request-Headers: X-Requested-With, accept, content-type
Vary: Accept-Encoding
Content-Length: 186
Content-Type: text/html

I've tried using Angular, jQuery, and a basic XMLHTTPRequest object, like so:

var data = "id=1234"
var request = new XMLHttpRequest({mozSystem: true})
request.onload = onSuccess;
request.open('GET', 'https://myurl.com' + '?' + data, true)
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
request.send()

...and it works in every browser except Firefox. Can anyone help with this?

This question is related to javascript firefox cors cross-domain

The answer is


Just a word of warnings. I finally got around the problem with Firefox and CORS.

The solution for me was this post

Setting CORS (cross-origin resource sharing) on Apache with correct response headers allowing everything through | Benjamin Horn

However Firefox was behaving really, really strange after setting those headers on the Apache server (in the folder .htaccess).

I added a lot of console.log("Hi FF, you are here A") etc to see what was going on.

At first it looked like it hanged on xhr.send(). But then I discovered it did not get to the this statement. I placed another console.log right before it and did not get there - even though there was nothing between the last console.log and the new one. It just stopped between two console.log.

Reordering lines, deleting, to see if there was any strange character in the file. I found nothing.

Restarting Firefox fixed the trouble.

Yes, I should file a bug. It is just that it is so strange so don't know how to reproduce it.

NOTICE: And, oh, I just did the Header always set parts, not the Rewrite* part!


Try this, it should solve your issue

  1. In your config.php, add www pre in your domain.com. For example:

    HTTP define('HTTP_SERVER', 'http://domain name with www/');
    HTTPS define('HTTPS_SERVER', 'http://domain name with www/');
    
  2. Add this to your .htaccess file

    RewriteCond %{REQUEST_METHOD} OPTIONS RewriteRule ^(.*)$ $1 [R=200,L]
    

In my case it was my ADBLOCKER! For some reason it was enabled on my localhost and causing this error in Firefox.

Disabling it or uninstalling the plugin should fix this.

In your case, it may not be an adblocker but another Firefox plugin. Test it out in incognito first with no plugins to determine if that is the issue and then systematically disable the plugins until you find the culprit.


For me, turns out I was setting Access-Control-Allow-Origin response header to a specific (and the correct) host.com but it had to be returned as http://host.com instead. What does firefox do? It silently swallows the GET request and returns a status 0 to the XHR, with no warnings output to the javascript console, whereas for other similar failures it would at least say something. Ai ai.


The files are self explanatory. Make a file, call it anything. In my case jq2.php.

<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
    // document is made ready so that the program starts when we load this page       
    $(document).ready(function(){

        // it tells that any key activity in the "subcat_search" filed will execute the query.
        $("#subcat_search").keyup(function(){

            // we assemble the get link for the direction to our engine "gs.php". 
            var link1 = "http://127.0.0.1/jqm/gs.php?needle=" + $("#subcat_search").val();

            $.ajax({
                url: link1,
                // ajax function is called sending the input string to "gs.php".
                success: function(result){
                    // result is stuffed in the label.
                    $("#search_val").html(result);
                }
            });
        })   

    });
</script>
</head>

<body>

<!-- the input field for search string -->
<input type="text" id="subcat_search">
<br>
<!-- the output field for stuffing the output. -->
<label id="search_val"></label>

</body>
</html>

Now we will include an engine, make a file, call it anything you like. In my case it is gs.php.

$head = "https://maps.googleapis.com/maps/api/place/textsearch/json?query="; //our head
$key = "your key here"; //your key
$hay = $_GET['needle'];

$hay = str_replace(" ", "+", $hay); //replacing the " " with "+" to design it as per the google's requirement 
$kill = $head . $hay . "&key=" . $key; //assembling the string in proper way . 
print file_get_contents($kill);

I have tried to keep the example as simple as possible. And because it executes the link on every keypress, the quota of your API will be consumed pretty fast.

Of course there is no end to things we can do, like putting the data into a table, sending to database and so on.


For posterity, also check server logs to see if the resource being requested is returning a 200.

I ran into a similar issue, where all of the proper headers were being returned in the pre-flight ajax request, but the browser reported the actual request was blocked due to bad CORS headers.

Turns out, the page being requested was returning a 500 error due to bad code, but only when it was fetched via CORS. The browser (both Chrome and Firefox) mistakenly reported that the Access-Control-Allow-Origin header was missing instead of saying the page returned a 500.


To debug, check server logs if possible. Firefox returns CORS errors in console for a whole range of reasons.

One of the reasons is also uMatrix (and I guess NoScript and similar too) plugin.


Just add

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

to the .htaccess file in the root of the website you are trying to connect with.


In my case CORS error was happening only in POST requests with file attachments other than small files.

After many wasted hours we found out request was blocked for users who were using Kaspersky Total Control.

It's possible that other antivirus or firewall software may cause similar problems. Kaspersky run some security tests for requests, but omits them for websites with SSL EV certificate, so obtaining such certificate should resolve this issue properly.

Disabling protection for your domain is a bit tricky, so here are required steps (as for December 2020): Settings -> Network Settings -> Manage exclusions -> Add -> your domain -> Save

The good thing is you can detect such blocked request. The error is empty – it doesn't have status and response. This way you can assume it was blocked by third party software and show some info.


I found that my problem was that the server I've sent the cross request to had a certificate that was not trusted.

If you want to connect to a cross domain with https, you have to add an exception for this certificate first.

You can do this by visiting the blocked link once and addibng the exception.


I came across this question having found requests in Firefox were being blocked with the message:

Reason: CORS request did not succeed

After pulling my hair out I found out that a newly installed Firefox extension, Privacy Badger, was blocking the requests.

If you come to this question after scratching your head, try checking to see what extensions you have installed to see if any of them are blocking requests.

See Reason: CORS request did not succeed on MDN for details.


I've found solution after 2 days :(.

Important note: when responding to a credentialed request, server must specify a domain, and cannot use wild carding.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials


If you don't have a 'real' certificate (and thus using a self-signed one), in Firefox you can go to:

Options > Privacy & Security > (scroll to the bottom) View Certificates > Servers > Add Exception...

There, fill in the location, eg: https://www.myserver:myport


I faced similar problem, and I think is valid to be registered how I fixed it:

I have a system built basically over Symfony 3. For self learn and performance purposes I decided to write few scripts using GoLang, also, an API with public access.

My Go API expects Json format params, and also return Json format response

To call those GoApi's I am using, most, $.ajax ( jQuery ) The first test was a deception: the (un)famous "Cross-Origin Request Blocked" pop up ! Then, I tried to set the "Access-Control-Allow-Origin: *" On apache conf, htaccess, php, javascript and anywhere I could find on google !

But, even, same frustrating error !!!

The Solution was simple : I had to make "POST" requests instead "GET" .

To achieve that I had to adjust both, GoLang and JavaScript to use GET ! Once it done, no more Cross-Origin Request Blocked for me !!!

Hope it Helps

PS:

I am using apache and Vhost, on Directory Block I have

  Header always set Access-Control-Allow-Origin "*"
  Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"

Remember : "*" means that you will accept requests from anyone !!! (Which may be a security lack ) In my case it is ok, because it will be an public API

PS2: My Headers

Response headers

Access-Control-Allow-Credentials    true
Access-Control-Allow-Headers    Authorization
Access-Control-Allow-Methods    GET, POST, PUT
Access-Control-Allow-Origin http://localhost
Content-Length  164
Content-Type    application/json; charset=UTF-8
Date    Tue, 07 May 2019 20:33:52 GMT

Request headers (469 B)

Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Connection  keep-alive
Content-Length  81
Content-Type    application/x-www-form-urlencoded; charset=UTF-8
Host    localhost:9003
Origin  http://localhost
Referer http://localhost/fibootkt/MY_app_dev.php/MyTest/GoAPI
User-Agent  Mozilla/5.0 (Macintosh; Intel …) Gecko/20100101 Firefox/66.0

If the aforementioned answers don't help then check whether the backend server is up and running or not as in my case the server crashed and this error turns out to be totally misleading.


Ubuntu Firefox giving CORS failed error when my request took more than 10 seconds to process.

Nothing to do with CORS. Problem is with ubuntu firefox configuration.

I have updated network.notify.changed to false which made this fix.


Mozilla Bugs Reference:

https://bugzilla.mozilla.org/show_bug.cgi?id=1238377

https://bugzilla.mozilla.org/show_bug.cgi?id=1235509


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 firefox

Drag and drop menuitems Class has been compiled by a more recent version of the Java Environment Only on Firefox "Loading failed for the <script> with source" Selenium using Python - Geckodriver executable needs to be in PATH Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property How to use the gecko executable with Selenium Selenium 2.53 not working on Firefox 47 Postman addon's like in firefox Edit and replay XHR chrome/firefox etc? How to enable CORS on Firefox?

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 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?