109

I'm calling this function from my asp.net form and getting following error on firebug console while calling ajax.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://anotherdomain/test.json. (Reason: CORS header Access-Control-Allow-Origin missing).

var url= 'http://anotherdomain/test.json';
        $.ajax({
            url: url,
            crossOrigin: true,
            type: 'GET',
            xhrFields: { withCredentials: true },
            accept: 'application/json'
        }).done(function (data) {
            alert(data);                
        }).fail(function (xhr, textStatus, error) {
            var title, message;
            switch (xhr.status) {
                case 403:
                    title = xhr.responseJSON.errorSummary;
                    message = 'Please login to your server before running the test.';
                    break;
                default:
                    title = 'Invalid URL or Cross-Origin Request Blocked';
                    message = 'You must explictly add this site (' + window.location.origin + ') to the list of allowed websites in your server.';
                    break;
            }
        });

I've done alternate way but still unable to find the solution.

Note: I've no server rights to make server side(API/URL) changes.

Tamir Abutbul
  • 7,301
  • 7
  • 25
  • 53
immayankmodi
  • 8,210
  • 9
  • 38
  • 55
  • 1
    Does `anotherdomain` support jsonp? Otherwise read this duplicate thread http://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource?rq=1 – Patrick Murphy Jul 07 '15 at 18:12
  • @PatrickMurphy, no `anotherdonain` doesn't support CORS. I'm getting `title = 'Invalid URL or Cross-Origin Request Blocked';` message. – immayankmodi Jul 08 '15 at 13:59
  • jsonp allows you to pass a callback parameter of some kind that allows you to receive the json wrapped data without `cors` – Patrick Murphy Jul 08 '15 at 15:15
  • @PatrickMurphy, Can you show me an working example? Because I tried everything was possible for me. Not sure why it wasn't working?? – immayankmodi Jul 08 '15 at 15:21
  • We need to know the api you are trying to contact, the jsonp specification would be in its documentation – Patrick Murphy Jul 08 '15 at 15:29
  • @PatrickMurphy, any suggestions? – immayankmodi Jul 13 '15 at 16:39

9 Answers9

91

This happens generally when you try access another domain's resources, and that other domain hasn't your domain on his cors origin whitelist.

To access ressources in a domain, it have to be previously authorized by the "cors origin" policy of that domain.

This is a security feature to avoid for example other domains to use ressources on your server or that can help to prevent website spoofing

You can fix this problem if you have control of both domains servers:

Solution 1: via .htaccess

You can write this in the .htaccess of the requested domain file:

=> Not recommended allow all domains

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

=> Recommended allow only expected domains

    <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin 'https://my-domain.example'
    </IfModule>

Solution 2: set headers the correct way

If you set this into the response header of the requested file, you will allow everyone to access the resources:

=> Not recommended allow all domains

Access-Control-Allow-Origin : *

OR

=> Recommended allow only expected domains

Access-Control-Allow-Origin : http://www.my-domain.example
TOPKAT
  • 6,667
  • 2
  • 44
  • 72
  • Hi @Sébastien Garcia-Roméo, I have added that to my .htaccess but I still get the same "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at..." issue. Do you know what could that be? Thank you – Jeff Feb 14 '16 at 12:02
  • This can be a lot of things...the best would be to have the requested media on the same server if possible... – TOPKAT Feb 23 '16 at 00:52
  • 2
    Jeff: make sure the mod_headers module is enabled in your server configuration. As you've noticed, gkubed's answer is subject to an IfModule test. In fact the best way is not to wrap it inside this test, so an error is raised if this module is not available on your server. – Fabien Haddadi Aug 23 '17 at 04:06
  • 1
    The emphasis in the answer is much appreciated. The placement of these headers on the "requested domain" (as opposed to the other) was the key for me. – yodarunamok Mar 22 '19 at 23:06
  • 1
    Should be the `Correct Answer` I have tried ` Header set Access-Control-Allow-Origin "*" ` and it works like a charm :) – Jodyshop Aug 21 '19 at 13:50
  • How does one fix this problem as a user? As someone who does not own either domain, how do i alter this setting in my browser? (Firefox, specifically?) – Sean Worle Dec 15 '21 at 20:13
  • @SeanWorle not sure it is possible. In some cases, you can use an extension to disable cors handling by the browser. But generally, this happens server side and cannot be impacted via code in front-end. If it was so, there would be a big security issue and cors wouldn't be of no use... – TOPKAT Dec 16 '21 at 09:38
10

Server side put this on top of <filename>.php:

header('Access-Control-Allow-Origin: *');

You can set specific domain restriction access:

header('Access-Control-Allow-Origin: https://www.example.com');
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
Ghanshyam Nakiya
  • 1,602
  • 17
  • 24
8

in your ajax request, adding:

dataType: "jsonp",

after line :

type: 'GET',

should solve this problem ..

hope this help you

Pegasus Cozza
  • 129
  • 1
  • 4
  • 8
    This is not a guaranteed fix, and will *only* work if the receiving domain is configured to respond in JSONP format. If the domain does not have CORS enabled, it's highly unlikely that JSONP will work. Also note that JSON and JSONP are not interchangable. – Rory McCrossan Dec 09 '16 at 20:16
  • @RoryMcCrossan how should the receiving domain respond to JSONP? (I'm using PHP.) I did a few searches but I'm not finding much. I think my issue might be more related to a WAF (Web Application Firewall) but I'm wondering if JSONP might somehow open up a workaround. – PJ Brunet Sep 09 '19 at 21:21
3

If you are using Express js in backend you can install the package cors, and then use it in your server like this :

const cors = require("cors");
app.use(cors());

This fixed my issue

klimqx
  • 139
  • 1
  • 2
1

You must have got the idea why you are getting this problem after going through above answers.

self.send_header('Access-Control-Allow-Origin', '*')

You just have to add the above line in your server side.

1

This worked for me:

Create php file that will download content of another domain page without using js:

<?
//file name: your_php_page.php
echo file_get_contents('http://anotherdomain/test.json');
?>

Then run it in ajax (jquery). Example:

$.ajax({
  url: your_php_page.php,
  //optional data might be usefull
  //type: 'GET',
  //dataType: "jsonp", 
  //dataType: 'xml',
  context: document.body
}).done(function(data) {

  alert("data");
  
}); 
Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
baron_bartek
  • 1,073
  • 2
  • 20
  • 39
0

You have to modify your server side code, as given below

public class CorsResponseFilter implements ContainerResponseFilter {
@Override
public void filter(ContainerRequestContext requestContext,   ContainerResponseContext responseContext)
    throws IOException {
        responseContext.getHeaders().add("Access-Control-Allow-Origin","*");
        responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");

  }
}
0

This can also happen if you use Google Cloud Armor and it denies the request due to a security policy like a SQL injection attempt. In that case it'll just return an HTML page with 403 Forbidden on it and none of the headers you'd expect:

HTTP/2 403 Forbidden
content-length: 134
content-type: text/html; charset=UTF-8
date: Tue, 28 Mar 2023 16:55:21 GMT
alt-svc: h3=":443"; ma=2592000,h3-29=":443"; ma=2592000
X-Firefox-Spdy: h2
dain
  • 6,475
  • 1
  • 38
  • 47
-2

In a pinch, you can use this Chrome Extension to disable CORS on your local browser.

Allow CORS: Access-Control-Allow-Origin Chrome Extension

Anthony
  • 13,434
  • 14
  • 60
  • 80