jquery ‘access-control-allow-origin’ - Why does my JavaScript get a “No 'Access-Control-Allow-Origin' header is present on the requested resource” error when Postman does not?




angular api (25)

I am trying to do authorization using JavaScript by connecting to the RESTful API built in Flask. However, when I make the request, I get the following error:

XMLHttpRequest cannot load http://myApiUrl/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

I know that the API or remote resource must set the header, but why did it work when I made the request via the Chrome extension Postman?

This is the request code:

$.ajax({
    type: "POST",
    dataType: 'text',
    url: api,
    username: 'user',
    password: 'pass',
    crossDomain : true,
    xhrFields: {
        withCredentials: true
    }
})
    .done(function( data ) {
        console.log("done");
    })
    .fail( function(xhr, textStatus, errorThrown) {
        alert(xhr.responseText);
        alert(textStatus);
    });

Answers

Because
$.ajax({type: "POST" - Calls OPTIONS
$.post( - Calls POST

both are different Postman calls "POST" properly but when we call it will be "OPTIONS"

For c# web services - webapi

Please add the following code in your web.config file under <system.webServer> tag. This will work

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
</httpProtocol>

Please make sure you are not doing any mistake in the ajax call

jQuery

$.ajax({
    url: 'http://mysite.microsoft.sample.xyz.com/api/mycall',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    type: "POST", /* or type:"GET" or type:"PUT" */
    dataType: "json",
    data: {
    },
    success: function (result) {
        console.log(result);    
    },
    error: function () {
        console.log("error");
    }
});

Angular 4 issue please refer : http://www.hubfly.com/blog/solutions/how-to-fix-angular-4-api-call-issues/

Note: If you are looking downloading content from third party website then this will not help you. You can try the following code but not JavaScript.

System.Net.WebClient wc = new System.Net.WebClient();
string str = wc.DownloadString("http://mysite.microsoft.sample.xyz.com/api/mycall");

CORS is for you.

CORS is "Cross Origin Resource Sharing" and is a way to send a cross-domain request. Now the XMLHttpRequest2 and Fetch API both support CORS.

But it has its limits. Server need to specific claim the Access-Control-Allow-Origin, and it can not be set to '*'.

And if you want any origin can send request to you, you need JSONP (also need to set Access-Control-Allow-Origin, but can be '*').

For lots of request way if you don't know what to choose, I think you need a fully functional component to do that. Let me introduce a simple component catta


If you are using a modern browser (> Internet Explorer9, Chrome, Firefox, Edge, etc.), it is very recommended you use a simple, but beautiful component, https://github.com/Joker-Jelly/catta. It has no dependencies, is less than 3 KB, and it supports Fetch, Ajax and JSONP with same dead-simple syntax and options.

catta('./data/simple.json').then(function (res) {
  console.log(res);
});

It also supports all the way to import to your project, like ES6 module, CommonJS and even <script> in HTML.


No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://sx.xyz.com' is therefore not allowed access.

I had also faced a similar problem with Cross Domain Data Exchange in the Ajax response as error undefined. But the response in header was Status Code:200 OK

Failed to load https://www.Domain.in/index.php?route=api/synchronization/checkapikey:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'https://sx.xyz.in' is therefore not allowed access.

The solution to get around it: In my case it was to call the function checkapikey() via Ajax to another domain and get the response with data to where the call has been made:

if (($this->request->server['REQUEST_METHOD'] == 'POST') && isset($this->request->server['HTTP_ORIGIN'])) {

        $this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
        $this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
        $this->response->addHeader('Access-Control-Max-Age: 1000');
        $this->response->addHeader('Access-Control-Allow-Credentials: true');
        $this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');

        $headers = getallheaders();
...
}

If you can deal with JSON in return, then try using JSONP (note the P at the end) for speaking between domains:

$.ajax({
  type: "POST",
  dataType: 'jsonp',
  ...... etc ......

Learn more about working with JSONP here:

The advent of JSONP — essentially a consensual cross-site scripting hack — has opened the door to powerful mashups of content. Many prominent sites provide JSONP services, allowing you access to their content via a predefined API.


https://github.com/Rob--W/cors-anywhere/ provides (Node.js) code you can use to set up and run your own CORS proxy. It’s actively maintained and provides a number of features for controlling the proxy behavior beyond just the basic sending of the correct Access-Control-* response headers.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS has details to explain how browsers handle cross-origin requests that client-side web applications make from JavaScript and what headers you must configure sending of by the server the request is made to, if you can.

In the case where a site you need to make a request to and get a response from doesn’t return the Access-Control-Allow-Origin response header, browsers are always going to block cross-origin requests made to it directly by your client-side JavaScript code from working. And so if the site is not one you control and can configure behavior for, the only thing that will work in that case is proxying the requests—either through your own proxy you run yourself or through an open proxy.

As mentioned in other comments here, there are good reasons for not trusting an open proxy with your requests. That said, if you know what you’re doing and you decide an open proxy works for your needs, https://cors-anywhere.herokuapp.com/ is one that’s reliably available, actively maintained, and that runs an instance of the https://github.com/Rob--W/cors-anywhere/ code.

As with other open proxies mentioned here (a couple of which at least don’t seem to be available any longer), the way it works is that instead of having your client code send a request directly to, e.g., http://foo.com you send it to https://cors-anywhere.herokuapp.com/http://foo.com and the proxy adds the necessary Access-Control-* headers to the response the browser sees.


A lot of times this happens to me from javascript to my php api, because one of a few reasons. I forget to put the <?php header('Access-Control-Allow-Origin: *'); ? is one. This is helpful for cross sub domain access. Another reason, is because in jQuery ajax request I am specifying a specific dataType and returning a different dataType, so it throws an error.

The Last and most prominent reasoning for this error is there is a parse error on the page you are requesting. If you hit that page url in your browser than more than likely you will see a parse error and you will have a line number to address the issue.

I hope this helps someone. It took me a while each time to debug this and I wish I had a checklist of things to verify.


If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.

When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:

Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.


You can bypass the problem by using YQL to proxy the request through Yahoo's servers. It is just a few lines of code:

var yql_url = 'https://query.yahooapis.com/v1/public/yql';
var url = 'your api url';

$.ajax({
    'url': yql_url,
    'data': {
        'q': 'SELECT * FROM json WHERE url="'+url+'"',
        'format': 'json',
        'jsonCompat': 'new',
    },
    'dataType': 'jsonp',
    'success': function(response) {
        console.log(response);
    },
});

Here's the link with an explanation: https://vverma.net/fetch-any-json-using-jsonp-and-yql.html


Most of these answers tell users how to add CORS headers to a server they control.

However, if you need data from a server you don't control in a webpage, one solution is to create a script tag on your page, set the src attribute to the api endpoint that doesn't have CORS headers, then load that data onto the page:

window.handleData = function(data) {
  console.log(data)
};

var script = document.createElement('script');
script.setAttribute('src','https://some.api/without/cors/headers.com&callback=handleData');
document.body.appendChild(script);

I had a problem with this when I used AngularJS to access my API. The same request worked in SoapUI 5.0 and ColdFusion. My GET method already had Access-Control-Allow-Origin header.

I found out that AngularJS makes a "trial" OPTIONS request. ColdFusion, by default, generates OPTIONS method, but it doesn’t have much, these headers specifically. The error was generated in response to that OPTIONS call, and not to my intentional call to GET. After I added OPTIONS method below to my API, the problem has been resolved.

<cffunction name="optionsMethod" access="remote" output="false" returntype="any" httpmethod="OPTIONS" description="Method to respond to AngularJS trial call">
    <cfheader name="Access-Control-Allow-Headers" value="Content-Type,x-requested-with,Authorization,Access-Control-Allow-Origin"> 
    <cfheader name="Access-Control-Allow-Methods" value="GET,OPTIONS">      
    <cfheader name="Access-Control-Allow-Origin" value="*">      
    <cfheader name="Access-Control-Max-Age" value="360">        
</cffunction>

I got this error with $http.get in Angular. I needed to use $http.jsonp instead.


I wish someone shared this site with me long ago http://cors.io/ it would have saved a ton of time compared to building and relying on my own proxy. However, as you move to production, having your own proxy is the best bet since you still control all aspects of your data.

All you need:

https://cors.io/?http://HTTP_YOUR_LINK_HERE


I had the following configuration, resulting in the same error, when requesting responses from the server.

Server-side: SparkJava --> provides the REST-API
Client-side: ExtJs6 --> provides Browser rendering

On the server-side I had to add this to the response:

Spark.get("/someRestCallToSpark", (req, res) -> {
    res.header("Access-Control-Allow-Origin", "*"); //important, otherwise its not working 
    return "some text";
 });

On the client-side I had to add this to the request:

Ext.Ajax.request({
    url: "http://localhost:4567/someRestCallToSpark",
    useDefaultXhrHeader: false, //important, otherwise its not working
    success: function(response, opts) {console.log("success")},
    failure: function(response, opts) {console.log("failure")}
});

If you are using Entity Framework, it seems that this error will sometimes be thrown even if you have CORS enabled. I figured out that the error occurred because of a missing finalization of the query. I'm hoping this will help others in the same situation.

The following code can throw the XMLHttpRequest cannot load http://myApiUrl/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. error:

using (DBContext db = new DBContext())
{
    return db.Customers.Select(x => new
    {
        Name = x.Name,
        CustomerId = x.CustomerId,
    });
}

To fix it, a finalization call like .ToList() or .FirstOrDefault() at the end of the query is required, like so:

using (DBContext db = new DBContext())
{
    return db.Customers.Select(x => new
    {
        Name = x.Name,
        CustomerId = x.CustomerId,
    }).ToList();
}

There's a cross-domain issue using Ajax. You must be sure you are accessing your files on the same http:// path without www. (or access from http://www. and post to the same path including www.) which the browser considers as another domain when accessing via a www. path, so you see where the problem is. You are posting to a different domain and the browser blocks the flow because of the origin issue.

If the API is not placed on the same host that you are requesting from, the flow is blocked, and you will need to find another way to communicate with the API.


On my website (based on .NET) I've just added this:

<system.webServer>
 <httpProtocol>  
    <customHeaders>  
     <add name="Access-Control-Allow-Origin" value="*" />  
     <add name="Access-Control-Allow-Headers" value="Content-Type" />  
     <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />  
    </customHeaders>  
  </httpProtocol>         
</system.webServer>

Big thanks to this video.


If you get this error message from the browser:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access

when you're trying to do an Ajax POST/GET request to a remote server which is out of your control, please forget about this simple fix:

<?php header('Access-Control-Allow-Origin: *'); ?>

You really need, especially if you only use JavaScript to do the Ajax request, an internal proxy who takes your query and sends it through to the remote server.

First in your JavaScript code, do an Ajax call to your own server, something like:

$.ajax({
    url: yourserver.com/controller/proxy.php,
    async: false,
    type: "POST",
    dataType: "json",
    data: data,
    success: function (result) {
        JSON.parse(result);
    },
    error: function (xhr, ajaxOptions, thrownError) {
        console.log(xhr);
    }
});

Then, create a simple PHP file called proxy.php to wrap your POST data and append them to the remote URL server as a parameters. I give you an example of how I bypass this problem with the Expedia Hotel search API:

if (isset($_POST)) {
  $apiKey = $_POST['apiKey'];
  $cid = $_POST['cid'];
  $minorRev = 99;

  $url = 'http://api.ean.com/ean-services/rs/hotel/v3/list?' . 'cid='. $cid . '&' . 'minorRev=' . $minorRev . '&' . 'apiKey=' . $apiKey;

  echo json_encode(file_get_contents($url));
 }

By doing:

echo json_encode(file_get_contents($url));

You are just doing the same query, but on the server side and after that, it should work fine.

Answer copied and pasted from NizarBsb


This is not a fix for production or when application has to be shown to the client, this is only helpful when UI and Backend development are on different servers and in production they are actually on same server. For example: While developing UI for any application if there is a need to test it locally pointing it to backend server, in that scenario this is the perfect fix. For production fix, CORS headers has to be added to the backend server to allow cross origin access.

The easy way is to just add the extension in google chrome to allow access using CORS.

(https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US)

Just enable this extension whenever you want allow access to no 'access-control-allow-origin' header request.

Or

In Windows, paste this command in run window

chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security

this will open a new chrome browser which allow access to no 'access-control-allow-origin' header request.


For completeness, Apache allows cors:

Header set Access-Control-Allow-Origin "http://www.allowonlyfromthisurl.com"
Header set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
Header set Access-Control-Max-Age "1000"
Header set Access-Control-Allow-Headers "x-requested-with, Content-Type, Accept-Encoding, Accept-Language, Cookie, Referer"

I was successfully able to solve (in my case for fonts) using htaccess but obviously, OP is asking little different. But you can use FileMatch pattern and add any sort of extension so that it won't give cros error.

<IfModule mod_headers.c>
  <FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|font.css|css)$">
    Header set Access-Control-Allow-Origin "*"
  </FilesMatch>
</IfModule>

https://httpd.apache.org/docs/2.4/mod/core.html#filesmatch


For the GoLang API:

First you can take a look at MDN CORS Doc to know what CORS is. As far as I know, CORS is about whether to allow Origin Of Request to access Server Resource or not.

And you can restrict which request origin can access the server by setting Access-Control-Allow-Origin at Header of Server Response.

For example, Setting following header in Server Response means that only request sent from http://foo.example can access your server:

Access-Control-Allow-Origin: http://foo.example

and following allow request sent from any origin(or domain):

Access-Control-Allow-Origin: *

And as I know in the error message, requested resource means resource of server, so No 'Access-Control-Allow-Origin' header is present on the requested resource. means you didn't set Access-Control-Allow-Origin header in your Server Response, or maybe you set but the origin of request isn't list in Access-Control-Allow-Origin so request is not allowed access:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

In GoLang, I use gorilla/mux package to build API server at localhost:9091, and I allow CORS by add "Access-Control-Allow-Origin", "*" to header of response:

func main() { // API Server Code
    router := mux.NewRouter()
    // API route is /people,
    //Methods("GET", "OPTIONS") means it support GET, OPTIONS
    router.HandleFunc("/people", GetPeople).Methods("GET", "OPTIONS")
    log.Fatal(http.ListenAndServe(":9091", router))
}

// Method of '/people' route
func GetPeople(w http.ResponseWriter, r *http.Request) {

    // Allow CORS by setting * in sever response
    w.Header().Set("Access-Control-Allow-Origin", "*")

    w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
    json.NewEncoder(w).Encode("OKOK")
}

And I use JavaScript in the client, at localhost:9092 make request by Chrome can succesfully get "OKOK" from Server localhost:9091.

function GetPeople() {
    try {
        var xhttp = new XMLHttpRequest();
        xhttp.open("GET", "http://localhost:9091/people", false);
        xhttp.setRequestHeader("Content-type", "text/html");
        xhttp.send();
        var response = JSON.parse(xhttp.response);
        alert(xhttp.response);
    }
    catch (error) {
        alert(error.message);
    }
}

Besides you can check your request/response header by tools like Fiddler.


Based on shruti's answer, I've created a shortcut of Chrome browser with needed arguments:


If you do NOT want to:

  1. Disable web security in Chrome
  2. Use JSONP
  3. Use a third party site to re-route your requests

and you are sure that your server has CORS enabled then (test CORS here: http://www.test-cors.org/)

Then you need to pass in origin parameter with your request. This origin MUST match the origin that your browser sends with your request.

You can see it in action here: http://www.wikibackpacker.com/app/detail/Campgrounds/3591

The edit functionality sends a GET & POST request to a different domain for fetching data. I set the origin parameter which resolves the issue. The backend is a mediaWiki engine.

tldr: Add "origin" parameter to your calls which must be the Origin parameter that your browser sends (you cannot spoof the origin parameter)


If you are using Node.js, try it:

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

More information: CORS on ExpressJS


Disable the chrome security.Create a chrome shortcut right click -> properties -> target, paste this "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="c:/chromedev"







jquery cors restful-authentication same-origin-policy flask-restless