EzDevInfo.com

cors

A node.js package that provides an Express/Connect middleware to enable Cross Origin Resource Sharing (CORS) with various options. cors middleware for dynamically or statically enabling cors in express/connect applications

"No 'Access-Control-Allow-Origin' header is present on the requested resource"

I am trying to do authorization using JavaScript by connecting to the RESTful API built in Flask.

As result I get:

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 tested authorization in 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);
    });

Source: (StackOverflow)

How to get a cross-origin resource sharing (CORS) post request working

I have a machine on my local lan (machineA) that has two web servers. The first is the in-built one in XBMC (on port 8080) and displays our library. The second server is a CherryPy python script (port 8081) that I am using to trigger a file conversion on demand. The file conversion is triggered by a AJAX POST request from the page served from the XBMC server.

  • Goto http://machineA:8080 which displays library
  • Library is displayed
  • User clicks on 'convert' link which issues the following command -

jQuery Ajax Request

$.post('http://machineA:8081', {file_url: 'asfd'}, function(d){console.log(d)})
  • The browser issues a HTTP OPTIONS request with the following headers;

Request Header - OPTIONS

Host: machineA:8081
User-Agent: ... Firefox/4.01
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Origin: http://machineA:8080
Access-Control-Request-Method: POST
Access-Control-Request-Headers: x-requested-with
  • The server responds with the following;

Response Header - OPTIONS (STATUS = 200 OK)

Content-Length: 0
Access-Control-Allow-Headers: *
Access-Control-Max-Age: 1728000
Server: CherryPy/3.2.0
Date: Thu, 21 Apr 2011 22:40:29 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Content-Type: text/html;charset=ISO-8859-1
  • The conversation then stops. The browser, should in theory, issue a POST request as the server responded with the correct (?) CORS headers (Access-Control-Allow-Origin: *)

For troubleshooting, I have also issued the same $.post command from http://jquery.com. This is where I am stumped, from jquery.com, the post request works, a OPTIONS request is sent following by a POST. The headers from this transaction are below;

Request Header - OPTIONS

Host: machineA:8081
User-Agent: ... Firefox/4.01
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Origin: http://jquery.com
Access-Control-Request-Method: POST

Response Header - OPTIONS (STATUS = 200 OK)

Content-Length: 0
Access-Control-Allow-Headers: *
Access-Control-Max-Age: 1728000
Server: CherryPy/3.2.0
Date: Thu, 21 Apr 2011 22:37:59 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Content-Type: text/html;charset=ISO-8859-1

Request Header - POST

Host: machineA:8081
User-Agent: ... Firefox/4.01
Accept: */*
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 115
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://jquery.com/
Content-Length: 12
Origin: http://jquery.com
Pragma: no-cache
Cache-Control: no-cache

Response Header - POST (STATUS = 200 OK)

Content-Length: 32
Access-Control-Allow-Headers: *
Access-Control-Max-Age: 1728000
Server: CherryPy/3.2.0
Date: Thu, 21 Apr 2011 22:37:59 GMT
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Content-Type: application/json

I can't work out why the same request would work from one site, but not the other. I am hoping someone might be able to point out what I am missing. Thanks for your help!


Source: (StackOverflow)

Advertisements

Access-Control-Allow-Origin wildcard subdomains, ports and protocols

I'm trying to enable CORS for all subdomains, ports and protocol.

For example, I want to be able to run an XHR request from http://sub.mywebsite.com:8080/ to https://www.mywebsite.com/*

Typically, I'd like to enable request from origins matching (and limited to):

//*.mywebsite.com:*/*


Source: (StackOverflow)

Why does canvas.toDataURL() throw a security exception?

Did I not get enough sleep or what? This following code

var frame=document.getElementById("viewer");
frame.width=100;
frame.height=100;

var ctx=frame.getContext("2d");
var img=new Image();
img.src="http://www.ansearch.com/images/interface/item/small/image.png"

img.onload=function() {
    // draw image
    ctx.drawImage(img, 0, 0)

    // Here's where the error happens:
    window.open(frame.toDataURL("image/png"));
}

is throwing this error:

SECURITY_ERR: DOM Exception 18

There's no way this shouldn't work! Can anyone explain this, please?


Source: (StackOverflow)

How to allow CORS in Express/Node.js?

I am trying to support CORS in my Node.js application that uses the Express.js web framework. I have read a Google group discussion about how to handle this, and read a few articles about how CORS works. First, I did this (code is written in CoffeeScript syntax):

app.options "*", (req, res) ->
  res.header 'Access-Control-Allow-Origin', '*'
  res.header 'Access-Control-Allow-Credentials', true
  # try: 'POST, GET, PUT, DELETE, OPTIONS'
  res.header 'Access-Control-Allow-Methods', 'GET, OPTIONS'
  # try: 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'
  res.header 'Access-Control-Allow-Headers', 'Content-Type'
  # ...

It doesn't seem to work. It seems like my browser (Chrome) is not sending the initial OPTIONS request. When I just updated the block for the resource I need to submit a cross-origin GET request to:

app.get "/somethingelse", (req, res) ->
  # ...
  res.header 'Access-Control-Allow-Origin', '*'
  res.header 'Access-Control-Allow-Credentials', true
  res.header 'Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS'
  res.header 'Access-Control-Allow-Headers', 'Content-Type'
  # ...

It works (in Chrome). This also works in Safari.

I have read that...

In a browser implementing CORS, each cross-origin GET or POST request is preceded by an OPTIONS request that checks whether the GET or POST is OK.

So my main question is, how come this doesn't seem to happen in my case? Why isn't my app.options block called? Why do I need to set the headers in my main app.get block?


Source: (StackOverflow)

How does Access-Control-Allow-Origin header work?

Apparently, I have completely misunderstood its semantics. I thought of something like this:

  1. A client downloads javascript code MyCode.js from http://siteA - the origin.
  2. The response header of MyCode.js contains Access-Control-Allow-Origin: http://siteB, which I thought meant that MyCode.js was allowed to make cross-origin references to the site B.
  3. The client triggers some functionality of MyCode.js, which in turn make requests to http://siteB, which should be fine, despite being cross-origin requests.

Well, I am wrong. It does not work like this at all. So, I have read http://en.wikipedia.org/wiki/Cross-origin_resource_sharing and attempted to read http://www.w3.org/TR/cors/.

One thing is sure - I still do not understand how am I supposed to use this header.

I have full control of both site A and site B. How do I enable the javascript code downloaded from the site A to access resources on the site B using this header?

P.S.

I do not want to utilize JSONP.


Source: (StackOverflow)

IE9 jQuery AJAX with CORS returns "Access is denied"

The following works in all browsers except IE (I'm testing in IE 9).

jQuery.support.cors = true;
...
        $.ajax(
            url + "messages/postMessageReadByPersonEmail",
            {
                crossDomain: true,
                data: {
                    messageId       : messageId,
                    personEmail     : personEmail
                },
                success: function() {
                    alert('marked as read');
                },
                error: function(a,b,c) {
                    alert('failed');
                },
                type: 'post'
            }
        );

I have another function which uses dataType: 'jsonp', but I don't need any data returned on this AJAX call. My last resort will be to return some jibberish wrapped in JSONP just to make it work.

Any ideas why IE is screwing up with a CORS request that returns no data?


Source: (StackOverflow)

Amazon S3 CORS (Cross-Origin Resource Sharing) and Firefox cross-domain font loading

There has been a long standing issue with Firefox not loading font from different origin than the current webpage. Usually, the issue arise when the fonts are served on CDNs.

Various solutions has been raised in other questions:

css @font-face not working with firefox, but working with chrome and IE

With the introduction of Amazon S3 CORS, is there a solution using CORS to address the font loading issue in Firefox?

Thanks in advance!

edit: It would be great to see a sample of the S3 CORS configuration.

edit2: I have found a working solution without actually understanding what it did. If anyone could provide more detailed explanations about the configs and the background magic that happens on Amazon's interpretation of the config, it will be greatly appreciated, as with nzifnab who put up a bounty for it.


Source: (StackOverflow)

Ajax using https on an http page

My site uses http and https protocol; it doesn't affect the content. My site uses jQuery ajax calls, which fills some areas on the page, too.

Now, I would like to do all ajax calls over https. (please dont ask me why :)) When I am on a page with https protocol, ajax requests are working. When I'm on a page with http protocol, I get a javascript error: Access to restricted URI denied

I know that this is a cross domain problem (in fact, it's a cross protocol problem), and I know that I should use the same protocol in ajax calls as on the current page.

Still, I want to all ajax calls to be https, and call them on a page that was served over http. Is there any workaround to achieve this (some json/proxy solution?), or is it simply impossible?


Source: (StackOverflow)

Access parent URL from iframe

Okay, I have a page on and on this page I have an iframe. What I need to do is on the iframe page, find out what the URL of the main page is.

I have searched around and I know that this is not possible if my iframe page is on a different domain, as that is cross-site scripting. But everywhere I've read says that if the iframe page is on the same domain as the parent page, it should work if I do for instance:

parent.document.location
parent.window.document.location
parent.window.location
parent.document.location.href

... or other similar combos, as there seems to be multiple ways to get the same info.

Anyways, so here's the problem. My iframe is on the same domain as the main page, but it is not on the same SUB domain. So for instance I have

http:// www.mysite.com/pageA.html

and then my iframe URL is

http:// qa-www.mysite.com/pageB.html

When I try to grab the URL from pageB.html (the iframe page), I keep getting the same access denied error. So it appears that even sub-domains count as cross-site scripting, is that correct, or am I doing something wrong?


Source: (StackOverflow)

CORS - What is the motivation behind introducing preflight requests?

Cross-origin resource sharing is a mechanism that allows a web page to make XMLHttpRequests to another domain (from wikipedia), and it's pretty important (from me :).

I've been fiddling with CORS for the last couple of days and I think I have a pretty good understanding of how everything works.

So my question is not about how CORS / preflight work, it's about the reason behind coming up with preflights as a new request type. I fail to see any reason why server A needs to send a preflight (PR) to server B just to find out if the real request (RR) will be accepted or not - it would certainly be possible for B to accept/reject RR without any prior PR.

After searching quite a bit I found this piece of information at www.w3.org (7.1.5):

To protect resources against cross-origin requests that could not originate from certain user agents before this specification existed a preflight request is made to ensure that the resource is aware of this specification.

I find this is the hardest to understand sentence ever. My interpretation (should better call it 'best guess') is that it's about protecting server B against requests from server C that is not aware of the spec.

Can someone please explain a scenario / show a problem that PR + RR solves better than RR alone?


Source: (StackOverflow)

Font from origin has been blocked from loading by Cross-Origin Resource Sharing policy

I'm receiving the following error on a couple of Chrome browsers but not all. Not sure entirely what the issue is at this point.

Font from origin 'https://ABCDEFG.cloudfront.net' has been blocked from loading by Cross-Origin Resource Sharing policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://sub.domain.com' is therefore not allowed access.

I have the following CORS Configuration on S3

<CORSConfiguration>
 <CORSRule>
   <AllowedOrigin>*</AllowedOrigin>
   <AllowedHeader>*</AllowedHeader>
   <AllowedMethod>GET</AllowedMethod>
 </CORSRule>
</CORSConfiguration>

The request

Remote Address:1.2.3.4:443
Request URL:https://abcdefg.cloudfront.net/folder/path/icons-f10eba064933db447695cf85b06f7df3.woff
Request Method:GET
Status Code:200 OK
Request Headers
Accept:*/*
Accept-Encoding:gzip,deflate
Accept-Language:en-US,en;q=0.8
Cache-Control:no-cache
Connection:keep-alive
Host:abcdefg.cloudfront.net
Origin:https://sub.domain.com
Pragma:no-cache
Referer:https://abcdefg.cloudfront.net/folder/path/icons-e283e9c896b17f5fb5717f7c9f6b05eb.css
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36

All other requests from Cloudfront/S3 work properly, including JS files.


Source: (StackOverflow)

CORS with jQuery and XDomainRequest in IE8/9

I am using CORS to call a cross domain API, however Internet Explorer is giving issues. CORS should be possible in IE8 and IE9 through the XDomainRequest object, however I can't get things to work..

JQuery refuses to provide native support for XDomainRequest, however several jQuery plugins are suggested to add this support. This topic suggest two such plugins: jQuery.XDomainRequest.js and xdr.js, which has been reported to work. Afaik, the plugins should automatically override behavior of jQuery.ajax. I found another plugin here.

I put a little demo pages with the respective plugins jQuery.XDomainRequest and xdr and jquery.ie.cors that perform ajax requests to a CORS enabled server. The pages are working in Chrome and Firefox, however IE8/9 instantly throw a permission denied error (even before making the request). This MSDN post suggest adding another handler xhr.onprogress = function() {}; but I tried this and it isn't working either.

Any clues what I am doing wrong? I have also tested with IE8 now using MS virtual server, but it has exactly the same problem.

Edit: OK so I figured out that part of the problem was that I was using POST over HTTPS. Apparently XDomainRequest does not allow CORS over HTTPS. I can switch to HTTP but I really need POST.

Edit2: See this issue on github for the end of this story. It turns out that when using HTTP POST, the xDomainRequest can only encode the request body (arguments) as text/plain. This pretty much makes it worthless, because everyone uses application/x-www-form-urlencoded or multipart/form-data.

Summary: I highly recommend not investing any time in XDomainRequest, because it is a terribly poor implementation with many limitations. It basically only really works for GET requests to non-ssl servers, so you might as well use jsonp or whatever.


Source: (StackOverflow)

So, JSONP or CORS?

My WebAPI was deployed in the Intranet environment. That means security was not my concern.

It seems that CORS is much more friendly to the client and easier to implement.

Any other concerns I might have missed?


Source: (StackOverflow)

enabling cross-origin resource sharing on IIS7

I recently ran into with posting Javascript requests to another domain. By default XHR posting to other domains is not allowed.

Following the instructions from http://enable-cors.org/, I enabled this on the other domain.

<?xml version="1.0" encoding="utf-8"?>
<configuration>
 <system.webServer>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*" />
      <add name="Access-Control-Allow-Methods" value="GET,PUT,POST,DELETE,OPTIONS" />
      <add name="Access-Control-Allow-Headers" value="Content-Type" />
    </customHeaders>
  </httpProtocol>
 </system.webServer>
</configuration>

enter image description here

Everything works fine now, however it is still return a 405 response before sending back the working 200 response.

Request URL:http://testapi.nottherealsite.com/api/Reporting/RunReport
Request Method:OPTIONS
Status Code:405 Method Not Allowed
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-GB,en-US;q=0.8,en;q=0.6
Access-Control-Request-Headers:origin, content-type, accept
Access-Control-Request-Method:POST
Connection:keep-alive
Host:testapi.nottherealsite.com
Origin:http://test.nottherealsite.com
Referer:http://test.nottherealsite.com/Reporting
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.89 Safari/537.1
Response Headersview source
Access-Control-Allow-Headers:Content-Type
Access-Control-Allow-Methods:GET,PUT,POST,DELETE,OPTIONS
Access-Control-Allow-Origin:*
Allow:POST
Cache-Control:private
Content-Length:1565
Content-Type:text/html; charset=utf-8
Date:Tue, 18 Sep 2012 14:26:06 GMT
Server:Microsoft-IIS/7.5
X-AspNet-Version:4.0.30319
X-Powered-By:ASP.NET

Update: 3/02/2014

There is a recently updated article in MSDN magazine. Detailing CORS Support in ASP.NET Web API 2.

http://msdn.microsoft.com/en-us/magazine/dn532203.aspx


Source: (StackOverflow)