Grunt connect task and middleware Access-Control-Allow-Origin

angularjs, grunt-contrib-connect, gruntjs, javascript, node.js

Solution

Try something like this:

connect: {
  options: {
    port: 9000,
    // Change this to '0.0.0.0' to access the server from outside.
    hostname: 'localhost',
    livereload: 35729,

    // remove next from params
    middleware: function(connect, options) {
      return [
        function(req, res, next) {
          res.setHeader('Access-Control-Allow-Origin', '*');
          res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
          res.setHeader('Access-Control-Allow-Headers', 'Content-Type');

          // don't just call next() return it
          return next();
        },

        // add other middlewares here 
        connect.static(require('path').resolve('.'))

      ];
    }
    },
    },

Problem

I would like to allow access to cross origin calls which I need to be able to perform rest API calls to the server. My connect grunt task is configured as follows: ``` connect: { options: { port: 9000, // Change this to '0.0.0.0' to access the server from outside. hostname: 'localhost', livereload: 35729, middleware: function(connect, options, next) { return [ function(req, res, next) { res.setHeader('Access-Control-Allow-Origin', '*'); res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); next(); } ]; } }, }, ``` When I run the grunt server I am getting `Cannot GET /`. Without the middleware configuration the app is working and the index file is loaded correctly. Could you guide me to what I am doing wrong or missing out? Some more details about my gruntfile is that I am using the yeoman angular seed app as my base to the app.

Original source

Related problems