CORS header 'Access-Control-Allow-Origin' missing

JqueryAjaxJsonCorsJsonp

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

This happens generally when you try access another domain's resources.

This is a security feature for avoiding everyone freely accessing any resources of that domain (which can be accessed for example to have an exact same copy of your website on a pirate domain).

The header of the response, even if it's 200OK do not allow other origins (domains, port) to access the ressources.

You can fix this problem if you are the owner of both domains:

Solution 1: via .htaccess

To change that, you can write this in the .htaccess of the requested domain file:

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

If you only want to give access to one domain, the .htaccess should look like this:

    <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin 'https://my-domain.tdl'
    </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 ressources:

Access-Control-Allow-Origin	: *

OR

Access-Control-Allow-Origin	: http://www.my-domain.com

Peace and code ;)

Solution 2 - Jquery

in your ajax request, adding:

dataType: "jsonp",

after line :

type: 'GET',

should solve this problem ..

hope this help you

Solution 3 - Jquery

Server side put this on top of .php:

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

You can set specific domain restriction access:

header('Access-Control-Allow-Origin: https://www.example.com')

Solution 4 - Jquery

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

  }
}

Solution 5 - Jquery

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.

Solution 6 - Jquery

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

Solution 7 - Jquery

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

Solution 8 - Jquery

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionimmayankmodiView Question on Stackoverflow
Solution 1 - JqueryTOPKATView Answer on Stackoverflow
Solution 2 - JqueryPegasus CozzaView Answer on Stackoverflow
Solution 3 - JqueryGhanshyam NakiyaView Answer on Stackoverflow
Solution 4 - JqueryRitesh KumarView Answer on Stackoverflow
Solution 5 - JqueryRaghvendra SinghView Answer on Stackoverflow
Solution 6 - Jquerybaron_bartekView Answer on Stackoverflow
Solution 7 - JqueryklimqxView Answer on Stackoverflow
Solution 8 - JqueryAnthonyView Answer on Stackoverflow