Git Product home page Git Product logo

cors's People

Contributors

a0viedo avatar abhishekbiswal avatar achhapolia10 avatar albertoleal avatar alex-grover avatar alex94cp avatar beneidel avatar chima1707 avatar chrisbujok avatar cwspear avatar damienklinnert avatar daniel08s avatar dougwilson avatar dracoblue avatar erisds avatar etiktin avatar focusaurus avatar jkasun avatar johanneswuerbach avatar kwizzn avatar linusu avatar luisegr avatar mafintosh avatar pgilad avatar shackpank avatar siyfion avatar tkopczuk avatar tomarad avatar troygoode avatar twistedstream avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cors's Issues

Version 2.5 does not add cors with subrouters

Version 2.4.2 works fine but newest version seems to work only without subrouters. Something like this won't work anymore.

app = express();
app.use(cors());
mainRouter = express.Router();
mainRouter.use('/items', itemsRouter);
...

cors doesn't apply to next(e) ...

Basically cross domain headers like origin and credentials doesn't work if rest API returns errors.

So for example if customer tries to use website as Unauthenticated 401. Cors doesn't apply to response. And if API is on subdomain - browser blocks requests

uploading image

Hi,

I am trying to upload an image using ajax from to the same server as the current page..but the image is downloaded from web. Currently chrome doesn't send any cookies (sesssion id or sid) back to server which in turn considers it as a different session. but If I upload a image from local system it sends the cookie header..I can see the list of header that are sent..

would your middleware work in such a case if I would put it as part of the upload url ...

Credentials flag error

Getting error in browser:

 XMLHttpRequest cannot load http://localhost:8080/. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://requirebin.com' is therefore not allowed access.

There doesn't seem to be any credential flags, so I'm a little confused.

Remote Address:127.0.0.1:8080
Request URL:http://localhost:8080/
Request Method:POST
Status Code:500 Internal Server Error

Request Headers:
POST / HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 105
Pragma: no-cache
Cache-Control: no-cache
accept: */*
Origin: http://requirebin.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.99 Safari/537.36
content-type: text/plain;charset=UTF-8
Referer: http://requirebin.com/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,ja;q=0.6
Cookie: [ ... ]
DNT: 1

Request Payload:
{"jsonrpc":"2.0","method":"eth_balanceAt","params":["0x407d73d8a49eeb85d32cf465507dd71d507100c1"],"id":1}

Response Headers:
HTTP/1.1 500 Internal Server Error
X-Powered-By: Express
Access-Control-Allow-Origin: *
Vary: Origin
Content-Type: application/json; charset=utf-8
Content-Length: 37
Date: Mon, 19 Jan 2015 01:06:19 GMT
Connection: keep-alive

CORS works for one route but not another when using app.use(cors(myOptions))

I am sure this is an issue with my implementation rather than this library but I am struggling to find out what the problem is.

I have a restful API and I configure it like so:

        var corsOptions = {
            origin: true,
            methods: ["ACCEPT", "GET", "POST", "DELETE", "OPTIONS"],
            allowedHeaders: ["Accept", "Content-Type"],
            maxAge: 3600,
            credentials: true
        };

        app.use(cors(corsOptions));

This happens before all routes and only seems to work for one of the routes I am testing, which is: http://localhost:2000/authentication via a POST request, with 1 custom middleware which basically converts the request body into a model and validates it. However if I go to http://localhost:2000/users via POST with the same custom middleware it never gets past the options response, which looks like:

HTTP/1.1 204 No Content
X-Powered-By: Express
Access-Control-Allow-Origin: http://localhost:3000
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: ACCEPT,GET,POST,DELETE,OPTIONS
Access-Control-Allow-Headers: Accept,Content-Type
Access-Control-Max-Age: 3600
Date: Fri, 07 Nov 2014 16:25:47 GMT
Connection: keep-alive

The client is running on port 3000 on localhost currently, so I am not sure if I need to allow other headers but both requests seem the same, they are both POST they both contain JSON and are both coming from same page, just one goes to /authentication one goes to /users I also cannot see any options for /authentication even if I use fiddler, not sure if maybe it worked originally so has cached it for the max age or something.

Any help would be great

does not work if use auth

The cors does not work if I use the auth as below, any idea?

var app = express();
app.use(express.basicAuth('foo', 'bar'));
app.use(cors());
<<

cors request hangs unexpectidly with express 3.0

using the below implementation of cors module causes unexpected hangs in express with POST..

var cors = require('cors');

var settings = {
  credentials: true,
  methods: ['GET','PUT','POST','OPTIONS'],
  origin: function(origin, callback) {
    if (!origin) return callback(null, false);
     if ( origin.indexOf("127.0.0.1") || origin.indexOf("localhost") ){
       callback(null, true);
     } else {
       callback(true, false);
     }
  }
};

app.use(cors(settings));

requests using curl and angular hang but process every now and then without errors thrown back but causes nodejs to hang

curl -v -i -X POST  -H "Expect:" -H "Origin: http://127.0.0.1:9000" -H "Access-Control-Request-Method: POST"   -H "Access-Control-Request-Headers: X-Requested-With" -F "file=@file" http://127.0.0.1:3000/store

Expose request object for dynamic origin

Access to the req object would be helpful if CORS configuration depends on the requested resource path for example. Lets say I want to protect my app paths by disallowing CORS requests, but still allow CORS requests for static assets. Without access to the req object, I can't do it.

Enable all CORS requests

Hi,

I have a problem with CORS requests. I can do a GET and a PATCH (for now) but when I try to do a POST the browser show me this message

XMLHttpRequest cannot load http://localhost:9000/1/applications. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9010' is therefore not allowed access.

I have 2 servers on http://localhost:9000 for the API and http://localhost:9010 for the website. On each servers I have enabled all CORS requests with there configurations like this

function Server(options) {
    this.httpServer = null;
    this.server = express();

    autoroute(
        this.server,
        {
            throwErrors: true,
            logger: Logger,
            routesDir: path.join(__dirname, "routes")
        }
    );

    this.server.set("port", options.port);
    this.server.set("name", options.name);

    this.server.use(express.bodyParser());
    this.server.use(express.methodOverride());
    this.server.use(cors(configuration.api_server));
    this.server.use(this.server.router);
    this.server.use(resourceNotFoundHandler);
    this.server.use(errorHandler);

    this.httpServer = http.createServer(this.server);
}
function Server(options) {
    this.httpServer = null;
    this.server = express();

    this.server.set("port", options.port);
    this.server.set("name", options.name);
    this.server.set("views", path.join(__dirname, "views"));
    this.server.set("view engine", "jade");

    this.server.use(express.compress());
    this.server.use(express.bodyParser());
    this.server.use(express.methodOverride());
    this.server.use(cors(configuration.web_server));
    this.server.use(this.server.router);
    this.server.use(express.static(path.join(__dirname, "public")));

    autoroute(
        this.server,
        {
            throwErrors: true,
            logger: Logger,
            routesDir: path.join(__dirname, "routes")
        }
    );

    this.httpServer = http.createServer(this.server);
}
{
    "development": {
        "api_server": {
            "origin": "http://localhost:9010",
            "methods": [ "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD" ]
        },
        "web_server": {
            "origin": "http://localhost:9000",
            "methods": [ "GET", "POST", "PUT", "PATCH", "DELETE", "HEAD" ]
        }
    }
}

Normally with this configuration all CORS must be enabled for all requests, no ?
I really need help for this.

Thanks

Cannot read property \'join\' of undefined

There is no check if methods is defined or not in the options.

function configureMethods(options) {
    var methods = options.methods;
    if (methods.join) {
      methods = options.methods.join(','); // .methods is an array, so turn it into a string
    }
    return {
      key: 'Access-Control-Allow-Methods',
      value: methods
    };
  }

Preflight success statusCode should be configurable

Hi,

we have currently problems in the communication with some Smart TVs. They crashs if getting a 204 status code for the preflight request and want to have a 200 status code.
Default value if not configured should be 204 for compatibility.

Headers only returned for OPTIONS request...?

While the correct headers are being returned for an OPTIONS request, I believe that they also need to be returned in the actual request response as well.

As an example, I am using the Access-Control-Allow-Credentials header, the OPTIONS request gets returned correctly, but the actual response does not. Here's the flow:

OPTIONS /api/login HTTP/1.1
Host: labellogiclive.jit.su
Connection: keep-alive
Access-Control-Request-Method: POST
Pragma: no-cache
Cache-Control: no-cache
Origin: http://labellogiclive.jit.su
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
Access-Control-Request-Headers: accept, origin, content-type
Accept: */*
Referer: http://labellogiclive.jit.su/user/login
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-GB,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

HTTP/1.1 204 No Content
x-powered-by: Express
vary: Accept-Encoding
access-control-allow-origin: http://labellogiclive.jit.su
access-control-allow-methods: POST
access-control-allow-headers: accept, origin, content-type
access-control-allow-credentials: true
access-control-allow-max-age: 3600
set-cookie: connect.sess=s%3Aj%3A%7B%7D.RZPCUBnPSt9dBV6%2FCAegqeEuY%2FlfIPlCWM%2Fm9HZS5L%2FUY4xJ9DkQXjPR%2FzN0VLheAaqlk59sgPWU%2FBgTiL9N4Q; Path=/; HttpOnly
date: Mon, 29 Apr 2013 08:35:28 GMT
connection: keep-alive

POST https://labellogiclive.jit.su/api/login HTTP/1.1
Pragma: no-cache
Accept: application/json, text/plain, */*
Referer: http://labellogiclive.jit.su/user/login
Origin: http://labellogiclive.jit.su
Cache-Control: no-cache
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
Content-Type: application/json;charset=UTF-8

Then I get an error:
XMLHttpRequest cannot load https://labellogiclive.jit.su/api/login. Credentials flag is true, but Access-Control-Allow-Credentials is not "true".

Looking at the server I can see it's returning a 200 OK response, but it never makes it to the browser. (I'm guessing that the error is generated prior to the response being logged)

Configuring CORS dynamically sends back a 500 for automated access

Using CORS v 2.8.1 I am configuring CORS with dynamic origin list using the example on the docs as below:

var express = require('express')
  , cors = require('cors')
  , app = express();

var whitelist = ['http://example1.com', 'http://example2.com'];
var corsOptions = {
  origin: function(origin, callback){
    var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
    callback(originIsWhitelisted ? null : 'Bad Request', originIsWhitelisted);
  }
};

app.get('/form', cors(corsOptions), function(req, res, next){
  ....
});

When accessing the server using curl ( with no origin header ) server sends back a 500 error. I would expect it to just add Access-Control-Allow-Origin header with white list rather blocking access and sending back a 500.

Whereas when configured statically as below it works fine:

var express = require('express')
  , cors = require('cors')
  , app = express();

var corsOptions = {
  origin: 'http://example.com',
  optionsSuccessStatus: 200 // some legacy browsers (IE11, various SmartTVs) choke on 204
};

Is this the intended behaviour ? Shouldn't it be just adding CORS headers for browsers rather than restricting access upon request ?

Ordering within middleware...?

Essentially I've encountered an issue with regards to where the cors middleware is injected, please see: expressjs/multer#25 for further details (and the resolution at the bottom). Is there a specific place it should be injected? First?

Add a change log

Consider adding a change log

It is necessary as people want to track changes

Leaking headers?

Let me preface this by saying that this module works great and seems generally well-thought-out, and it's not at all clear to me what the best practice for exposing Access-Control-* headers is in every situation (or even if there is a consensus on best practice), but it seems to me that the code leaks information in a couple of ways:

  1. If the origin setting is set to a string (a "fixed" origin), then the Access-Control-Allow-Origin header is always returned with that value, regardless of the request origin.
  2. All of the other Access-Control-* headers are always returned regardless of whether the request origin is in the whitelist.

I'm fairly certain that an AJAX request from a non-whitelisted origin will not have access to these headers (that is, the browser will not provide them in the response), but you can still see them by, for example, looking in the "Network" tab of the Chrome developer console.

I don't see the rationale for exposing the criteria for acceptance to a requestor that doesn't meet those criteria. For example, if you had an admin app on some subdomain ("xyzadmin.myapp.com") that you didn't want to be made public, and you have your main app ("myapp.com") accepting cross-origin requests only from that domain, it doesn't seem right that by making an AJAX request to myapp.com from any random domain you could get the Access-Control-Allow-Origin header with the value xyzadmin.myapp.com and thus learn about that existence of the admin server. Similarly, if someone made an AJAX PUT request to some route and it was rejected for not matching the whitelist of available methods, why would you want that person to be given the list of available methods that are allowed?

What's even more curious to me is that in this module's implementation, specifying the origin setting as an array always does what I would consider the best behavior, which is to not send the Access-Control-Allow-Origin header at all if the requesting origin doesn't match the whitelist. It does this even if the array only has one item.

Absent a good reason to send back all this information, I'd propose that any request whose origin doesn't match the whitelist should be responded to without any Access-Control-* headers at all, and I'd be happy to submit a patch to make things work that way. I'd even go so far as to say that requests that do match the origin whitelist should only be given as much information as is necessary to satisfy the browser (that is, instead of Access-Control-Allow-Methods showing all the allowable methods, only reflect the one that was actually used in the request), but I'm not quite as bullish on that point.

I'm also fully prepared to hear that I don't know what I'm talking about and that there is a perfectly reasonable explanation for the current behavior. I wouldn't be surprised if it's hidden in the W3C CORS spec, clear as mud.

Missing request data events

Is there a reason for the request.pause() / resume() calls? Because (in node 0.10) request handlers now miss data events. Removing the pause/resume from the cors module resolves the problem.

Any thoughts on this?

Allow CORS on static file serving

Hello, and thank you for this wonderful lib, dynamic options are the greatest.

Now to problem.
I have this configuration,
app.options('*', cors());
All static files are loading well but the font files which returns CORS issue.
Static file serving is done this way.
app.use(express.static(myParh))

Thank you.

Why run request handlers "successfully" if the request fails CORS?

If a request fails CORS as specified by this module's configuration, the module will not set the CORS headers on the response. However, it will still call next, causing the usual request handler to run. This can be a problem if the request is expensive to handle, or has side effects.

What is the thinking behind this? It seems reasonable to terminate the request immediately, or at least call next with an error, if it's going to fail client-side due to the lack of CORS headers.

Here is a small project demonstrating this issue: https://github.com/mixmaxhq/cors-response-tester.

Option to set `Timing-Allow-Origin`

In order to allow the resource timing API to work correctly, the Timing-Allow-Origin must be set to allow certain portions of the resource timing API to be used.

Can we add an option to allow this header to be set, matching the value reflected for the Access-Control-Allow-Origin header?

Passing a frozen object as config object generates `Cannot assign to read only property 'origin' of object` TypeError

This line modifies the option object passed to cors.
But if that object is immutable (using Object.freeze() for example), then the following error is generated:

TypeError: Cannot assign to read only property 'origin' of object '#<Object>'
        at /path/to/project/node_modules/cors/lib/index.js:228:36
        at originCallback (/path/to/project/node_modules/cors/lib/index.js:218:15)
        at /path/to/project/node_modules/cors/lib/index.js:223:13
        at optionsCallback (/path/to/project/node_modules/cors/lib/index.js:204:9)

Note that config package (which seems to be a popular package) if freezing the config by default.

Current workaround:

// assuming that `corsConfig` is frozen
app.use({... corsConfig}); // ... or  app.use(Object.assign({}, corsConfig).. or _.extend({}, corsConfig)...

Let me know if you think that it's something that you want to address, I can give it a try and open a PR.

Unexpected behaviour

Hello, my cors are working fine when making an API call from a browser app. If the domain is in the whitelist, the corsOptions origin callback sends true, otherwise it block as expected. But when I call the API from a REST console or a node CLI program, the call works, even if origin is undefined and the corsOptions origin callback sends false.

Shouldn't it fail? Otherwise how can I block calls that don't come from the whitelisted origins? Can I choose dynamically?

Thanks!

npm install failed on node v0.10.15

I get this following error

npm WARN package.json [email protected] No repository field.
npm http GET https://registry.npmjs.org/cors
npm http 200 https://registry.npmjs.org/cors
npm http GET https://registry.npmjs.org/cors/-/cors-1.0.1.tgz
npm http 404 https://registry.npmjs.org/cors/-/cors-1.0.1.tgz
npm ERR! fetch failed https://registry.npmjs.org/cors/-/cors-1.0.1.tgz
npm ERR! Error: 404 Not Found
npm ERR!     at WriteStream.<anonymous> (/home/XXX/nvm/v0.10.15/lib/node_modules/npm/lib/utils/fetch.js:57:12)
npm ERR!     at WriteStream.EventEmitter.emit (events.js:117:20)
npm ERR!     at fs.js:1596:14
npm ERR!     at /home/XXX/nvm/v0.10.15/lib/node_modules/npm/node_modules/graceful-fs/graceful-fs.js:103:5
npm ERR!     at Object.oncomplete (fs.js:107:15)
npm ERR! If you need help, you may report this log at:
npm ERR!     <http://github.com/isaacs/npm/issues>
npm ERR! or email it to:
npm ERR!     <[email protected]>

npm ERR! System Linux 3.2.13-grsec-xxxx-grs-ipv6-64
npm ERR! command "/home/XXX/nvm/v0.10.15/bin/node" "/home/XXX/nvm/v0.10.15/bin/npm" "install" "cors"
npm ERR! cwd /home/XXX/tmp2
npm ERR! node -v v0.10.15
npm ERR! npm -v 1.3.5
npm ERR!
npm ERR! Additional logging details can be found in:
npm ERR!     /home/XXX/tmp2/npm-debug.log
npm ERR! not ok code 0

"Access-Control-Allow-Origin" is not added to headers

It started with having problem for CORS between my front-end (angular2) and back-end (expressjs). Some StackOverflow recommend to use cors-package (for answers in 2016 against those from 2013-2014).

I've used following configuration and CORS still not adding "Access-Control-Allow-Origin":

cors            = require('cors'),

const originsWhiteList = {
  "http://localhost:3001": true   // front-end development port
};

const corsOptions = {
  origin: function(origin, callback) {
    callback(originsWhiteList[origin] ? null : 'Bad Request', originsWhiteList[origin]);
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE']
}
.
.
.
// just right before other routes
app.use(cors(corsOptions));
app.options('/api/v1/*', cors());

this should be classified as bug, right ?

the exact error:

XMLHttpRequest cannot load http://localhost:3000/api/v1/todos. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3001' is therefore not allowed access. The response had HTTP status code 403.

Using with socket.io

Hi,

I have an express app using cors hosted by Nodejitsu acting as a REST API, so it serves no HTML, but JSON. Some requests are bound with socket.io. On another server, I have an Angular Requirejs app (very.ink) serving HTMLs and calling the rest API (Nodejitsu). All non-socket requests are processed but the socket.io requests are not. I have tested locally (Angular app at localhost:8000) with the same results.

My Express app settings for cors:

// app.js
var express    = require('express');
var app        = express();
var cors = require('cors');
var bodyParser = require('body-parser');
var morgan     = require('morgan');
var port       = process.env.PORT || 8080; 

// Attaching socket.io
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.set('socketio', io); 
app.set('server', server);
var whitelist = ['http://very.ink/#/', 'http://very.ink', 'very.ink', 'localhost:8000'];
var corsOptions = {
 origin: function(origin, callback){
   var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
   callback(null, originIsWhitelisted);
 }
};

app.use(cors(corsOptions));
// configure body parser
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.get('server').listen(port);

I keep getting error

 XMLHttpRequest cannot load http://<MYAPP>/socket.io/?EIO=3&transport=polling&t=1423147457220-0. The 'Access-Control-Allow-Origin' header contains multiple values 'http://evil.com/, *', but only one is allowed. Origin 'http://very.ink' is therefore not allowed access.

How should I change the cors settings? Thank you very much.

Best, Trang

So, headers only returned for OPTIONS request... again?

i'm installed this. Add to app.js "app.use(cors());"
Trying to GET my CORS headers with curl, but got:

HTTP/1.1 200 OK
X-Powered-By: Express
X-Request-Id: 37a5b307-886d-4da0-97de-f4d1d5c6c32c
Cache-Control: max-age=0, private
Expires: -1
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Content-Length: 411
ETag: W/"19b-6y0fduS9wFWuJQobNUC5SQ"
Date: Tue, 27 Sep 2016 06:52:06 GMT
Connection: keep-alive

All OPTIONS request with CORS, another request without CORS.
What i'm doing wrong?

"Vary: Origin" not set if Origin is not allowed.

When using the 'array' or 'regexp' notation of whitelisted origins we don't send 'Vary: Origin' if the passed Origin is not allowed.

This results in failed CORS responses being cached by the downstream cache and subsequently served even for proper request (which would contain Vary: Origin, but downstream won't fetch them, as it has the cached response it's looking for).

This behavior is seen with e.g. Google Cloud cache, with the additional side effect of a failed CORS response overwriting all the previously cached successful responses that contained "Vary: Origin".

#105 PR for your consideration.

safari can not request cors.

blow is my cors option.


cors : function() {
return {
origin : function(origin, callback) {
callback(null, origin === undefined || config.isWhiteList(origin)/always true/);
},
credentials : true,
methods : ["GET", "POST", "DELETE", "PUT", "UPDATE", "OPTIONS", "HEAD"],
exposedHeaders : ['Origin', 'Upgrade', 'Content-Encoding', 'Content-Range', 'Accept-Ranges', 'Range', 'Content-Type', 'Authorization',
'X-Forwarded-For', 'Connection', 'Host', 'Content-Length', 'X-Real-IP', 'X-Requested-With', 'Set-Cookie', 'Cookie'],
allowedHeaders : ['Origin', 'Upgrade', 'Content-Encoding', 'Content-Range', 'Accept-Ranges', 'Range', 'Content-Type', 'Authorization',
'X-Forwarded-For', 'Connection', 'Host', 'Content-Length', 'X-Real-IP', 'X-Requested-With', 'Set-Cookie', 'Cookie']
}
}


and this is used as middleware


app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended : false }));
app.use(cookieParser());
app.use(cors(config.cors()));

app.use(sessionStore(app, config));

it works fine chrome env. but not working in safari.
( always refresh cookie values in safari )

how can i handle this?

Should CORS deny access from curl requests?

I'm attempting to use the CORS module to block curl requests (or other rest client requests, such as chrome's excellent Postman). But it's not working.

Im guessing that CORS is only respected when making a request from a browser, and that a server to server request not protected with cors. If this is correct, how would I block a cross server request?

Stopped working after adding ssl certificate

It worked fine for months with http. When added ssl certificate using Letsencrypt (https://letsencrypt.org/) I started getting this error:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

SSL certificate issue is mentioned a little in https://github.com/expressjs/cors/issues/45 but doesn't provide enough info to solve my problem.

My questions:

  1. Does changing from http to https require any additional config changes?
  2. Could be adding ssl certificate the reason of this error?
  3. What is the solution? Buy normal ssl certificate? Can you recommend any cheap ones that you sure it works?

Error: listen EADDRINUSE

Hi

How can I specify which ports to allow?
I want to talk between 8444 and 8443, but when I add

app.listen(8444, function(){
  		console.log('CORS-enabled web server listening on port 8444');
	});

or either of them, and get the error in the title.

Access-Control-Expose-Headers

Would just like to double check this issue. In my use case I have a CSRF token in the headers. Now to have that token accessible by the client then I need to use 'Access-Control-Expose-Headers'. This middle ware does not offer the functionality to add that header, correct?

Multiple cors middlewares on same request?

I have an API where I want every path to be CORS-enabled for all origins except for /auth/connect/twitter because it uses a cookie based session.

I was wondering if it would be possible to make it so that the last cors() middleware always overrides precedent ones. E.g.

router.use(cors())
router.use(cors({ origin: 'http://mydomain.com' }))

should set the Access-Control-Allow-Origin to http://mydomain.com. Is that possible?

Response Headers Missing

First off, let me just say thanks for creating a (potentially) very useful bit of middleware!

The issue I'm having is that none of the headers seem to be injected into the response at all; even though I think my configuration is correct.

I have my routes in routes.js, along with the cors middleware:

'use strict';

/**
 * Module dependencies.
 */

var cors = require('cors');

var corsOptions = {
  origin: true,
  methods: ['POST'],
  credentials: true,
  maxAge: 3600,
  enablePreflight: true
};

module.exports = function (app) {

  /**
   * Session Routes
   */
  var login = require('../routes/login');
  app.post('/api/login', cors(corsOptions), login.login);
};

Here's the request from the client:

OPTIONS /api/login HTTP/1.1
Host: label-logic-live.herokuapp.com
Connection: keep-alive
Access-Control-Request-Method: POST
Origin: http://label-logic-live.herokuapp.com
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31
Access-Control-Request-Headers: accept, origin, content-type
Accept: */*
Referer: http://label-logic-live.herokuapp.com/user/login
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-GB,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

and the response:

HTTP/1.1 200 OK
Accept-Ranges: bytes
Cache-Control: public, max-age=0
Content-Encoding: gzip
Content-Type: text/html; charset=UTF-8
Date: Thu, 25 Apr 2013 10:14:21 GMT
Etag: "4045-1366883997000"
Last-Modified: Thu, 25 Apr 2013 09:59:57 GMT
Set-Cookie: connect.sess=s%3Aj%3A%7B%7D.RZPCUBnPSt9dBV6%2FCAegqeEuY%2FlfIPlCWM%2Fm9HZS5L%2FUY4xJ9DkQXjPR%2FzN0VLheAaqlk59sgPWU%2FBgTiL9N4Q; Path=/; HttpOnly
Vary: Accept-Encoding
X-Powered-By: Express
transfer-encoding: chunked
Connection: keep-alive

And then I get a normal error in the browser console:

XMLHttpRequest cannot load https://label-logic-live.herokuapp.com/api/login. Origin http://label-logic-live.herokuapp.com is not allowed by Access-Control-Allow-Origin. /user/login:1

Cookies get set despite invalid origin when credentials: true is specified

Hello! I have a scenario which I would like to get some thoughts on. I would like my XHR's to drop cookies, and so I use the "credentials: true" option. However, when hitting my API from an invalid origin, the value for the Access-Control-Allow-Credentials header remains true. This causes an interesting thing to occur, where the browser "rejects" the request as it should, but it still drops my cookies. I would think that if the Access-Control-Allow-Origin header signifies that the request is from an invalid origin, that it should also ignore the Set-Cookies header despite the value of the Access-Control-Allow-Credentials header, but that is apparently not the case.

So, what I would propose as a solution would be to have either 1) set the credentials header to false whenever the origin is invalid, or 2) at least have a configuration option for such a behavior.

If you agree, I am more than happy to submit a pull request. What I am unsure of is whether this should be considered a default behavior, or an opt-in/config behavior. Or, if I'm just being stupid and have completely misunderstood a core principle of CORS, that would be a valid response too :)

Thanks!
Dave

POST does nothing after pre-flight

*** Sorry - my bad. It works just fint

In POSTMAN it works so I'm pretty sure it's a cors thing.
The OPTIONS method returns a 204 and Chrome dev tools says "Fetch complete: POST..."

This is the code:

var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');
var cors = require('cors');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080;        // set our port

app.get('/api/list', function(req, res) {
	res.json({ result: 'ok' });	
});

app.options('/api/list', cors());
app.post('/api/list', cors(), function(req, res) {
	res.json({ result: 'ok' });	
});
app.listen(port);
console.log('Magic happens on port ' + port);

when configured to reflect Access-Control-Request-Headers, should also use Vary: Access-Control-Request-Headers

When the middleware is configured to reflect the request value of Access-Control-Request-Headers in the response value of Access-Control-Allow-Headers (as it is in the default configuration), it should also include Vary: Access-Control-Request-Headers in the response. Without this header, it's possible to trigger a situation where a downstream cache responds to an OPTIONS request using a cached response from an OPTIONS request with a different Access-Control-Request-Headers value. This could potentially result in either a permissible OPTIONS request being refused, or a non-permissible request being allowed.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤ī¸ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.