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:

$.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);
    });

30 comments

@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

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

Short and clean one!

@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 https://github.com/troygoode/node-cors#configuration-options for
// details on its contents. The following is a basic permissive set of options:
httpNodeCors: {
 origin: "*",
 methods: "GET,PUT,POST,DELETE"
},

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__)
CORS(app)

@app.route("/")
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.

@SD. 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: *');

@SD. 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 ??

@shady sherif 2016-05-09 03:47:18

@DivyeshKanzariya you can use cors html5rocks.com/en/tutorials/cors

@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

@Qadir Hussain 2019-08-28 11:06:34

Awesome. this worked for me :)

@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) {
  console.log(data)
};

var script = document.createElement('script');
script.setAttribute('src','https://some.api/without/cors/headers.com&callback=handleData');
document.body.appendChild(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).

@duhaime 2019-09-13 18:11:10

Agreed. @AngelT why would you want to fetch a script that you don't intend to run?

@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:

Node.js

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

var options = {
    method: 'POST',
    uri: 'http://api.posttestserver.com/post',
    body: {
        some: 'payload'
    },
    json: true // Automatically stringifies the body to JSON
};

app.get('/', function (req, res) {
    rp(options)
    .then(function (parsedBody) {
        res.send(parsedBody)
    })
    .catch(function (err) {
        res.send(err)
    });
});
app.listen(port);

JavaScript

axios.get("http://localhost:3000/").then((res)=>{
    console.log('================res====================');
    console.log(res);
    console.log('====================================');
})

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

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

$.ajax({
      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":"192.168.1.1"})';

In this case, the backend response is like:

jQuery331009526199802841284_1533646326884({"ip":"192.168.1.1"})

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

$.ajax({
      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:

get_ip({"ip":"192.168.1.1"})

@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 app.py 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.

<?php
    header("Content-Type: text/plain");
    if (isset($_GET["cnic"]))
    {
        $page = file_get_contents("https://external.domain.com/api/verify/" . $_GET["cnic"]);
        echo $page;
    }
    else
    {
        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: 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.wikinomad.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)

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

Are your referring to this example code from main.min.js?: t.post("https://wiki.wikinomad.com/api.php?origin=https://ww‌​w.wikinomad.com", 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

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 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("http://mysite.microsoft.sample.xyz.com/api/mycall");

@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 https://www.myotherdomain.com

@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:

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

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

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

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"

@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

@Nishanth ॐ 2018-03-03 05:28:02

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();
...
}

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

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

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

@jkpd 2015-09-17 13:05:01

cors.io/?u=HTTP_YOUR_LINK_HERE (small correction)

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

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

@Anirudha 2015-12-10 06:47:25

Only get requests allowed i guess..

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

@KingRider 2016-04-15 15:05:27

try too https://crossorigin.me/http://example.com

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

Golden for testing! Have been struggeling for a long time to load some test data from foo.bar.whatever, 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 cors.io Port 80 (Apache for this? LOL)

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

1 more, add https to cors.io

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

If you get the over quota message, you can simply use: crossorigin.me/YOUR_LINK_HERE it offers similar services!

@JoeCodeFrog 2018-03-27 15:59:04

crossorigin.me 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 cors.io 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? stackoverflow.com/questions/46063304/…

@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'] = '*'
end

@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, 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.

@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: "http://websitelink.com", headers: "*", methods: "*")] but it is not working. Any idea? forums.asp.net/p/2117965/…

@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: "http://clientaccessingapi.com", headers: "*", methods: "*")]

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

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.

@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:

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

@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 google.com/complete/search?client=firefox&q=query

@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 "*"
  </FilesMatch>
</IfModule>

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

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

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

@sideshowbarker 2017-03-12 07:01:34

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.

Related Questions

Sponsored Content

6 Answered Questions

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

12 Answered Questions

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

17 Answered Questions

29 Answered Questions

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

13 Answered Questions

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

20 Answered Questions

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

8 Answered Questions

7 Answered Questions

Sponsored Content