By Mr Jedi

2013-11-17 19:29:06 8 Comments

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:

    type: "POST",
    dataType: 'text',
    url: api,
    username: 'user',
    password: 'pass',
    crossDomain : true,
    xhrFields: {
        withCredentials: true
    .done(function( data ) {
    .fail( function(xhr, textStatus, errorThrown) {


@Maiden 2019-08-09 11:43:15

If your server is a Springboot App then please add this annotation in your rest controller at the top - @CrossOrigin

It should work now . Thanks

Details: know about the CORS - cross origin resource sharing . You can allow a particular Rest API using the mentione crossorigin annotation and provide the access .

@USer22999299 2019-09-05 08:51:54

Short and clean one!

@shruti 2015-03-04 06:42:07

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.


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


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.

@Ruby_Pry 2015-05-14 18:09:31

I am trying to use that CORS tool but I dont know how to use it. Can you help me with that?

@shruti 2015-05-15 09:52:43

@Ruby_Pry just add the extension from the url given above and then you can see the CORS app icon on top left side of your chrome browser, click on that, you will see a popup where you can ON it whenever u want to allow access through CORS.

@Taersious 2015-09-24 17:55:06

This is great but clients can't be asked to launch chrome this way to enforce an internal requirement for a webservice call.

@shruti 2015-09-25 15:47:54

@Taersious yes you are right, for that we need to set CORS headers at server end.

@James Kirkby 2016-04-28 11:10:33

this shouldn't be accepted as an answer, installing a third party plugin to fix your app, rather than understanding CORS and fixing your app, how will other people use your api? will you make them all install this plugin

@wagwanJahMan 2016-05-10 12:54:25

I installed this extension and did a request, than checked the request in fiddler, the following was specified -> Origin: . Looks like this extension is changing the Origin to

@sms 2016-05-11 11:07:58

This extension is working like a charm. But really what they are doing internally? Is there a way to do the same in Javascript or Jquery way rather than using a plugin ?

@shruti 2016-05-11 12:12:46

@sms why do want to do in javascript, what is exact use case ?

@sms 2016-05-11 12:25:17

@shruti Since I am going to give the application to the end user, I need to give separate plugins for each browser. It is also not possible to add header in my target server. If there is any change to be done, it should be done in my client application from where the ajax call is made.

@shruti 2016-06-24 05:28:34

@sms I think u can use jsonp, m not sure. look at this link may be it helps.

@watsonic 2017-01-10 06:20:39

worked well for me. i am using this with Cordova in debugging via a "browser" platform via cordova run browser

@frooble 2017-03-13 19:43:12

I found the extension doesn't fill the bill. It seems Chrome does not like the fact that the Access-Control-Allow-Origin: * when withCredentials is used: <blah blah> has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'null' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribut

@jtcotton63 2017-03-24 00:44:24

I think this is a really great answer if you don't need a permanent fix or if you only need CORS disabled temporarily. That's what I needed, and this solution worked great. Obviously, this could never be considered a permanent solution.

@Cerin 2017-06-20 03:21:15

You're recommending people to disable all security in their browser just to run your apps code? No no no no no no!!!

@Andy Fusniak 2017-08-08 10:34:24

I can't believe this answer got any upvotes or credence at all. Instead of solving the problem, you've just disable crippled the browse security. Stupid solution.

@Adam Hughes 2017-10-19 19:48:46

This answer is fine. For dev work, this got me up-and-running asap and I will come back and find the proper fix later...

@TechnoCrat 2017-11-16 09:38:58

This one is great, it helped me to test my code in local machine where as on server front end and back end code is on same domain so this issue anyway not going to come

@Codiee 2017-12-20 14:02:40

Great, "chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security" this worked for now.

@CPHPython 2018-02-16 18:20:58

You can be safer and define more customizations (defining which origin web/localserver is allowed to make CO requests, Access-Control-Allow-Headers and Access-Control-Allow-Methods) through Moesif's Chrome plugin. Shruti, if you can include this in your answer, I believe it'd help even more people.

@Sergio A. 2019-07-05 10:36:25

Thanks for that windows command; worked like a charm. Obviously, this should be used only for development purposes.

@Newteq Developer 2019-07-09 12:57:44

Definitely not the recommended way to do this, but for testing something quickly, this approach works perfectly and it's super helpful. CORS should still be set up on the project correctly for anything outside of development, and even in development.

@shady sherif 2014-12-03 20:24:24

Warning: Using this answer on production may cause a security issue that your API/service could be called by anyone has the URL including attackers. you have to use sessions and cookies for authentication to prevent your API/service against this attack. Your API/service is vulnerable to cross-site request forgery (CSRF).

It's very simple to solve if you are using PHP. Just add the following script in the beginning of your PHP page which handles the request:

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

If you are using Node-red you have to allow CORS in the node-red/settings.js file by un-commenting the following lines:

// The following property can be used to configure cross-origin resource sharing
// in the HTTP nodes.
// See for
// details on its contents. The following is a basic permissive set of options:
httpNodeCors: {
 origin: "*",

If you are using Flask same as the question; you have first to install flask-cors

$ pip install -U flask-cors

Then include the flask cors in your app

from flask_cors import CORS

A simple app will look like

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)

def helloWorld():
  return "Hello, cross-origin-world!"

For more details, you can check the flask documentation

@llazzaro 2014-12-20 19:25:19

and it's not secure

@shady sherif 2014-12-28 07:24:30

Yes I know it is about Js, But I solved it using the PHP very easily! About the security issue if JS is currently on another domain, you can go through the JS to allow its cross origin why you didn't find that isn't secure?

@meagar 2014-12-30 06:12:55

You shouldn't turn off CORS because you don't know what its for. This is a terrible answer.

@ZurabWeb 2015-02-26 16:37:57

Even though it might not be secure, the question was not about security, but how to accomplish the task. This is one of the options that a developer has to choose from when dealing with cross-domain AJAX requests. It helped me resolve the issue, and for my application, I don't care where the data came from. I sanitize all the input with PHP on the destination domain, so, if someone wants to post some junk to it, let them try. The main point here is, cross-domain AJAX can be allowed from the destination domain. +1 for the answer.

@Saurin Dashadia 2015-03-02 06:59:17

I had the same issue on same domain as I have full site using https but only one page is using http method and any request from http page results in same error. I wanted to solve it with JS only as adding such header wasnt my first choice. I have tried all above solutions like placing crossDomain:true, withCredentials: true and also followed CORS but no solution worked ever. Then finaly I have added header('Access-Control-Allow-Origin: *');

@Saurin Dashadia 2015-03-02 07:00:09

One thing I would like to add here is. If you are using header('Access-Control-Allow-Origin: *'); you need to remove withCredentials: true from ajax request.

@Thomas F. 2015-10-15 14:55:13

While I agree with the general message Piero is giving, that it's not specifically about security, but security is a concern. I think this should have at least said something like "This is generally bad! Don't do this unless you know what you're doing! Here's more documentation on it: ...", and maybe briefly explain why. I would hate for someone to come on here and just think "Oh, I can just add/adjust this header and I'm good!" and not know the full ramifications. I mean, it's kind of on them to research and all, but still.

@Divyesh Kanzariya 2016-04-28 05:48:46

@shadysherif how to same things using JavaScript any idea ??

@Pradeep Srivastava 2017-02-09 06:30:45

@shadysherif It worked it can be use in non-transaction data procession comes in handy nice!!

@Epirocks 2017-02-27 17:38:54

Noone cares about security when developing locally, CORS just gets in the way. You might have a node.js server running on a different port/server than the one you are requesting data from. But in production they may all run off the same server in which case CORS doesn't cause a problem.

@Ari Waisberg 2017-03-17 19:38:18

I like this answer... I have the same issue and it solves it... He explained there are some security issues, but that's another problem and let everyone individualy think and resolve that issue...

@Chuck Le Butt 2019-05-11 17:54:23

This is a perfect answer if you DO know what you're doing (ie. testing locally). Thanks

@CeeJay 2019-09-12 07:40:18

Magic! Can you please explain how does this actually work?

@duhaime 2018-01-31 15:13:51

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) {

var script = document.createElement('script');

@Angel T 2018-02-08 06:52:56

Excellent answer, but if script is not in correct format, then you can't reach its code (script.text= empty). What to do in this case? How to reach its code?

@Angel T 2018-02-08 07:16:27

How to prevent the execution of the script (maybe as comment it all)?

@Angel T 2018-02-08 08:14:24

And another interesting thing: Only IE11 with Enabled "Access data sources across domains" can access cross-domain (without of need to control server to modificate Origin!. All rest major browsers can't

@mahemoff 2019-09-13 15:09:24

This will execute the remote JavaScript, if it's a valid script, but it won't let you see the content. It remains just a script tag with a URL as an attribute.

@mahemoff 2019-09-13 15:10:27

@AngelT you can't prevent it running (and to my point above, running it is about the only practical reason to make a remote script tag).

@KT Works 2018-07-17 09:45:40

Maybe is it a little bit complicated, but you can use a web server to route the request.

With Node.js you don't have this problem. I am not an expert in Node.js. So I don't know if this is clean code.

But this works for me.

Here is a little example:


var rp = require('request-promise');
var express = require('express'),
    app = express(),
    port = process.env.PORT || 3000;

var options = {
    method: 'POST',
    uri: '',
    body: {
        some: 'payload'
    json: true // Automatically stringifies the body to JSON

app.get('/', function (req, res) {
    .then(function (parsedBody) {
    .catch(function (err) {



@Alexey Kolotsey 2018-08-07 13:38:10

In a JSONP request you should catch "jsonpCallback" and send it back:

      url: lnk,
      type: 'GET',
      crossDomain: true,
      dataType: 'jsonp',
      success: function (ip) { console.log(ip.ip); },
      error: function (err) { console.log(err) }

On the backend side (if you use PHP as backend):

echo $_GET['callback'].'({"ip":""})';

In this case, the backend response is like:


But you can set a "jsonpCallback" manually on the frontend and catch it on the backend side:

      url: lnk,
      type: 'GET',
      crossDomain: true,
      dataType: 'jsonp',
      jsonpCallback: 'get_ip',
      success: function (ip) { console.log(ip.ip); },
      error: function (err) { console.log(err) }

In this case the backend response is like:


@Ben Watts 2018-08-11 10:46:00

In case you want to fix this on the backend (in Flask), rather than on the front end, I would totally recommend the Flask CORS Python package. Flask CORS

With one simple line in your you can automatically insert the standard, allow any origin header, or customise it as required.

@inter18099 2018-12-26 08:45:03

You may not want to use JSONP, because it has some limitation such as it doesn't support the POST method.

You just need to enable CORS on your server.

If you use Spring Boot, read this post: Enabling Cross Origin Requests for a RESTful Web Service

In short, just put:

@CrossOrigin(origins = "*")

before your @RequestMapping annotation.

@user1913615 2019-01-09 14:10:24

I'm using AngularJS and Spring both on localhost (different ports) and had the same problem, adding @CrossOrigin(origins = "*") as mentioned below solved it.

@Muhammad Saqib 2019-02-05 15:34:19

I created a simple bridge in my own domain which fetches and shows the content from an external domain.

    header("Content-Type: text/plain");
    if (isset($_GET["cnic"]))
        $page = file_get_contents("" . $_GET["cnic"]);
        echo $page;
        echo "";

Now, instead of accessing external domain in Ajax, I placed the URL of this bridge file.

You should adjust the Content-Type according to your needs. If the data is in JSON then use header("Content-Type: application/json");.

@Chandan Kumar 2019-03-17 10:53:13

In my case I was using Spring Boot as the service, you can add use cross origin annotation on the responsible operation:

@CrossOrigin(origins = "http://localhost:4200")
@RequestMapping(value = "getFoo", method = RequestMethod.GET)
public ResponseEntity getFoo(){
    // Do something

@Ujjwal 2019-04-12 07:52:03

This solution will definitely work for you. Add a custom message handle:

public class CustomHeaderHandler : DelegatingHandler
    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
        var referrer = request.Headers.Referrer;
        if (referrer != null && !response.Headers.Contains("Access-Control-Allow-Origin"))
            response.Headers.Add("Access-Control-Allow-Origin", referrer.Scheme + "://" + referrer.Authority);
        return response;

Register in webapiconfig.cs:

config.MessageHandlers.Add(new CustomHeaderHandler());

And if you are using SignalR then add this code in the globle.asax.cs file:

protected void Application_BeginRequest(object sender, EventArgs e)
    var referrer = Request.UrlReferrer;
    if (Context.Request.Path.Contains("signalr/") && referrer != null)
        Context.Response.AppendHeader("Access-Control-Allow-Origin", referrer.Scheme + "://" + referrer.Authority);

@Ganesh Krishnan 2016-07-07 04:26:02

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:

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:

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)

@CODE-REaD 2018-02-15 20:18:48

Are your referring to this example code from main.min.js?:"‌​", n, o).then(function(e) {.... If so, isn't it true that this way of specifying an origin requires that the PHP being served from the "backend" is coded to support it, and this answer will not work otherwise?

@Ganesh Krishnan 2019-01-19 17:55:34

@CODE-REaD, yes that's correct that the backend needs to support CORS as well.

@George Livingston 2016-12-13 13:02:58

$.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

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

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


    url: '',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    type: "POST", /* or type:"GET" or type:"PUT" */
    dataType: "json",
    data: {
    success: function (result) {
    error: function () {

Angular 4 issue please refer :

Note: If you are looking for 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("");

@Andre Mesquita 2017-05-22 13:41:53

This config solved same error on Wordpress at Azure Services. Thanks.

@pechar 2017-06-09 08:30:06

I would suggest using a specific origin value to avoid requests from external domains. So for example instead of * use

@bachstein 2017-09-27 15:03:35

Perhaps you can copy the resource from the production server to the development server, and have the URL to the resource to adjust dynamically. In that way you would be reading always from the same origin, eliminating the cross origin exception.

@Flash 2017-10-26 13:23:34

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:

    async: false,
    type: "POST",
    dataType: "json",
    data: data,
    success: function (result) {
    error: function (xhr, ajaxOptions, thrownError) {

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 = '' . '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

@Stephan Weinhold 2018-06-09 20:14:59

This is a big security risk!

@mwallisch 2018-06-13 11:15:05

@stephan-weinhold in case you would actually sanitize the url parameters. would it still be a security risk? why?

@yu yang Jian 2017-11-19 12:19:24

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

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();"GET", "http://localhost:9091/people", false);
        xhttp.setRequestHeader("Content-type", "text/html");
        var response = JSON.parse(xhttp.response);
    catch (error) {

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

@zak 2017-11-20 00:05:18

For completeness, Apache allows cors:

Header set Access-Control-Allow-Origin ""
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"

@zak 2017-11-20 00:05:58

Anybody can add to that ^

@Rohit Dhiman 2018-09-18 06:56:41

Worked for Apache and laravel 5.4

@Nɪsʜᴀɴᴛʜ ॐ 2018-03-03 05:28:02

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '' 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
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin '' 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();

@yoshyosh 2015-07-21 22:08:57

I wish someone shared this site with me long ago 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:

@Sebastialonso 2015-08-21 16:33:45

What are the downsides of this? Are those guys intercepting my data?

@Li3ro 2015-09-01 06:32:03

..This application is temporarily over its serving quota. Please try again later.

@Daniel Alexandrov 2015-10-16 14:07:01

I don't think sending your data over 3rd party proxy is a good idea

@evelynhathaway 2016-02-20 07:52:14

One downside is they are sometimes overloaded, as they are now. This application is temporarily over its serving quota. Please try again later.

@Automatico 2016-04-18 12:52:55

Golden for testing! Have been struggeling for a long time to load some test data from, this is the solution to that problem.

@Ulysses Alves 2016-06-17 18:18:10

How to implement our own service for what this website does?

@nsantana 2016-08-12 04:29:46

@UlyssesAlves, it's simple. Just implement a service service that receive a URL as parameter, then download the content of this url and return to the client.

@Nino Škopac 2016-11-01 18:35:40

The bad: The server is temporarily unable to service your request due to maintenance downtime or capacity problems. Please try again later.. The ugly: Apache/2.4.7 (Ubuntu) Server at Port 80 (Apache for this? LOL)

@X Sham 2018-02-06 10:08:07

1 more, add https to

@Yoav Hortman 2018-03-27 15:45:40

If you get the over quota message, you can simply use: it offers similar services!

@JoeCodeFrog 2018-03-27 15:59:04 is my to-go service for proxy testing my stuff

@Brandito 2018-06-29 02:31:44

@jkpd 'nope' response

@swv 2018-07-16 21:25:23

downvote only because of the obvious security problem

@etlds 2018-11-01 19:39:26

My question is why domain can go through?

@rohillasarthak 2019-05-01 10:50:47

this site is suspected as phishing by avast

@No Refunds No Returns 2017-09-07 14:49:02

Popular question -- Another thing to look at if you've read this far and nothing else has helped. If you have a CDN such as Akamai, Limelight or similar, you might want to check the cache key you have for the URI of the resource. If it does not include the Origin header value you may be returning a response cached when requested from another Origin. We just spent half a day debugging this. The CDN configuration was updated to only include the Origin value for a few select domains that are ours and set it to null for all others. This seems to work and allows browsers from our known domains to view our resources. Certainly all the other answers are prerequisites to getting here but if the CDN is the first hop from your browser this is something to review.

In our case we could see some requests making it to our service but not nearly the volume the site was sending. That pointed us to the CDN. We were able to go back and see the original request was served from a direct request, not part of a browser AJAX call and the response header Access-Control-Allow-Origin was not included. Apparently the CDN cached this value. The Akamai CDN configuration tweak to consider the Origin request header value as part of the match seems to have made it work for us.

@sideshowbarker 2017-09-07 21:19:59

In your case, wouldn’t sending the Vary: Origin response header have achieved the same effect?…

@No Refunds No Returns 2017-09-07 22:42:14

Yes but we don't. A service exposed to the world can be DOS'ed via cache explosion by sending bogus values. Akamai has some help in this area to reduce DOS exposure. My point is that you can do everything listed and still have a problem because of caching.

@Quentin 2017-09-13 08:39:58

The question says "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 not an answer to the question that was asked.

@No Refunds No Returns 2017-09-13 14:54:56

@Quentin You are so RIGHT! however this is the #1 hit for many searches on this topic, there are already a variety of answers that vary from the exact question yet provide useful information AND this was what we discovered on Sept 7 after exhausting all of the threads. I appreciate your downvote. Future readers will be also able be able to weigh whether or not this "not an answer" was helpful by voting, perhaps even differently from you. There is at least one other person who has already publicly disagreed with your opinion. Will be interesting to see how the voting goes from here........

@No Refunds No Returns 2018-08-21 17:42:27

+5/-1 Thanks again masses.

@张健健 2017-08-11 07:39:34

For Ruby on Rails server in application_controller.rb, add this:

after_action :cors_set_access_control_headers

def cors_set_access_control_headers
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
  headers['Access-Control-Allow-Headers'] = '*'

@Quentin 2017-09-13 08:40:09

The question says "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 not an answer to the question that was asked.

@Jelly 2017-01-19 14:40:32

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, 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) {

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

@Si8 2017-03-24 14:12:16

I have an IIS site which is local that is hosting my API. I have an external site which is accessed outside the local network. I am trying to execute the API from the external site, I have CORS enabled for the external site (e.g. [EnableCors(origins: "", headers: "*", methods: "*")] but it is not working. Any idea?…

@Rizwan ali 2017-04-03 18:42:44

I have resolved this by enabling CORS for the client URL accessing the web API, and it worked successfully.

For example:

[EnableCors(origins: "", headers: "*", methods: "*")]

@FrenkyB 2017-08-19 15:13:00

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

     <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" />  

Big thanks to this video.

@Quentin 2017-09-13 08:40:04

The question says "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 not an answer to the question that was asked.

@Gavin 2014-02-22 00:42:04

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

  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.

@Gaizka Allende 2014-05-15 09:36:47

With NodeJs with datatype json worked, with ASP.Net this was the culprit

@Prabu Raja 2014-11-13 00:28:45

Be aware jsonp doesn't work for POST content. More discussions here.

@fatlog 2015-08-07 15:06:05

How does this have so many up votes when you cant use jsonp with POST requests?!?!

@noob 2016-10-06 03:56:12

When you use JSONP, $.ajax will ignore type, so it's always GET which means this answer will always work.

@Csaba Toth 2016-11-06 03:35:56

@fatlog Because most people access it with GET

@Csaba Toth 2016-11-06 03:41:51

It's easier to use jsonp than reconfigure the other hosting server. This is a time saver.

@m.qayyum 2017-04-17 10:47:14

This works to get response from

@Rory McCrossan 2017-09-07 10:19:31

Also note that JSONP is not directly interchangeable with JSON. You need the server to return data in JSONP format too. Simply changing the dataType in the AJAX request settings alone isn't going to work.

@Quentin 2017-09-13 08:40:30

The question says "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 not an answer to the question that was asked.

@carobnodrvo 2017-07-11 19:36:57

Just to mention another way of "bypassing" it - AJAX proxy. Send request to your server to fetch the data from another origin and send the request back to you.

I prefer this approach over JSONP because it has some potential security issues.

@Quentin 2017-09-13 08:40:41

The question says "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 not an answer to the question that was asked.

@Danish 2017-06-15 08:39:49

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 "*"

@camnesia 2016-11-21 14:59:36

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 = '';
var url = 'your api url';

    'url': yql_url,
    'data': {
        'q': 'SELECT * FROM json WHERE url="'+url+'"',
        'format': 'json',
        'jsonCompat': 'new',
    'dataType': 'jsonp',
    'success': function(response) {

Here's the link with an explanation:

@saber tabatabaee yazdi 2017-06-08 16:16:34

but after seconds ... all the other codes run then it initialize.

@Travis Heeter 2017-02-13 17:46:32

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

Related Questions

Sponsored Content

7 Answered Questions

[SOLVED] XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header

9 Answered Questions

12 Answered Questions

[SOLVED] No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

14 Answered Questions

[SOLVED] How does Access-Control-Allow-Origin header work?

29 Answered Questions

[SOLVED] Access-Control-Allow-Origin Multiple Origin Domains?

21 Answered Questions

[SOLVED] Response to preflight request doesn't pass access control check

17 Answered Questions

7 Answered Questions

Sponsored Content