How can I add CORS-Headers to a static connect server?
Asked Answered
P

4

26

I am writing a little demo web server delivering static html,css and javascript. The server looks like

(function () {
    "use strict";

    var http = require("http");
    var connect = require('connect');
    var app = connect()
        .use(connect.logger('dev'))
        .use(connect.static('home'));

    var server = http.createServer(app);
    server.listen(9999, function () {
        console.log('server is listening');
    });
})();

My client side javascript makes ajax calls to a different server. How can I add

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

to my server response, so that the client side javascript can do the ajax call?

Pelmas answered 15/6, 2013 at 14:19 Comment(0)
D
18

Had a bit of trouble figuring this one out since express has spoiled me.

Take a look at enable cors. Basically what you need to be doing is add Access-Control-Allow-Origin to the domain you want to enable cors on. response.setHeaders is perfect for this task.

Another thing to note is that connect has no way to handle routes. If your app needs to have different routes then you will probably have to write logic for each of them and add res headers to the ones on which you want to enable cors. You can use req.url for it.

var http = require("http");
var connect = require('connect');

var app = connect()

    .use(connect.logger('dev'))

    .use(connect.static('home'))

    .use(function(req, res){

    res.setHeader("Access-Control-Allow-Origin", "http://example.com");
    res.end('hello world\n');

 });

var server = http.createServer(app);

server.listen(9999, function () {

    console.log('server is listening');
});

This is the response I got in chrome dev tools

HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://example.com
Date: Sat, 15 Jun 2013 16:01:59 GMT
Connection: keep-alive
Transfer-Encoding: chunked
Donica answered 15/6, 2013 at 14:39 Comment(1)
Thanks a lot, absolutely perfect!Pelmas
B
7

I hope this will help:

//CORS middleware
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', config.allowedDomains);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');

    next();
}

//...
app.configure(function() {

    app.use(allowCrossDomain);
    app.use(express.static(__dirname + '/public'));
});

More detail: How to allow CORS?

Bloodthirsty answered 25/12, 2013 at 21:20 Comment(1)
res.header must be res.setHeader for connect middleware 2.0 and greaterLikely
H
5

express.static takes a configuration object. You can provide the property setHeaders and from that function you can set headers for the response:

    app.use(express.static('public', {
      setHeaders: function setHeaders(res, path, stat) {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET');
        res.header('Access-Control-Allow-Headers', 'Content-Type');
      }
    }))

The parameters to this function are:

  • res, the response object.
  • path, the file path that is being sent.
  • stat, the stat object of the file that is being sent.

I wish that the request were available here so that I could conditionally set the CORS headers based upon the Origin header.

Haldeman answered 2/10, 2017 at 3:18 Comment(0)
O
2

The easiest method, if you are using gulp would be to use gulp plugin called "gulp-connect" and "connect-modrewrite" and define a new gulptask to redirect a particular api. This is to make the apache act as a Proxy for the particular api, to bypass the pre-flight request, inorder to avoid CORs issue. I used the following gulp task to overcome this problem.

var connect = require('gulp-connect'),
    modRewrite = require('connect-modrewrite');
/**
* Proxy Config
*/
gulp.task('connect', function () {
  connect.server({
    root: ['./.tmp', './.tmp/{folderLocations}', './src', './bower_components'],
    port: 9000,
    livereload: true,
    middleware: function (connect, opt) {
      return [
        modRewrite([
          '^/loginProxy/(.*)$ http://app.xyzdomain.com/service/login/auth/$1 [P]'
        ])
      ];
    }
  });
});
Ossicle answered 30/8, 2015 at 18:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.