gruntjs / grunt-contrib-connect

Start a static web server.
http://gruntjs.com
MIT License
714 stars 146 forks source link

Setting CORS header does not work #150

Closed leolux closed 9 years ago

leolux commented 9 years ago
livereload: {
    options: {
      open: true,
      middleware: function (connect) {
        var middlewares = [
            //Enable CORS
            connect().use('/', function (req, res, next) {
              res.setHeader('Access-Control-Allow-Origin', '*');
              next();
            }),
            connect.static('.tmp'),
            connect().use(
              '/bower_components',
              connect.static('./bower_components')
            ),
            connect.static(appConfig.app)
          ];
        return middlewares;
      }
    }
  }

I tried many different combinations, searched for examples and documentation without success. In the example above the CORSE header "Access-Control-Allow-Origin" does not get send by the server.

The only way tested, where the CORSE header has actually been sent to the client uses the function "middlewares.unshift(function (req, res, next) {..}". But it does not find the resources under /.tmp and /bower_components. So the static linking of those folders gets broken this way.

However, I couldn't find a working solution for the current verison of Gruntfile.js generated by yeoman angular. Missing this header is an issue because it prevents connection to local websocket endpoints.

jamesplease commented 9 years ago

Try:

connect().use(function (req, res, next) {
  res.setHeader('Access-Control-Allow-Origin', '*');
  next();
})
leolux commented 9 years ago

Yes, that's it. Thank you a lot for your answer!

daniel-macleod commented 9 years ago

Hey guys I know this was posted a while ago but I've been trying to get this working all day and still havent'. I have this exact code in my gruntfile.js and when I open the browser there is an error saying: Cannot GET /index.html

connect: { options: { //port: 8080, livereload: true, hostname: "localhost", base: "." }, livereload: { options: { open: true, middleware: function (connect) { var appConfig = { app: require('./bower.json').appPath || 'app', dist: 'dist' }; var middlewares = [ //Enable CORS connect().use(function (req, res, next) { res.setHeader('Access-Control-Allow-Origin', ''); res.setHeader('Access-Control-Allow-Methods', ''); next(); }), connect.static('.tmp'), connect().use( '/bower_components', connect.static('./bower_components') ), connect.static(appConfig.app) ]; return middlewares; } } } }, ... Thanks in advance

cemsbr commented 7 years ago

I get Warning: middlewares.each is not a function Use --force to continue. Is there anything else to do?

k13elle commented 6 years ago

me too