Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grunt Server: Not supporting CORS, gives error

I have a server setup and everything was going fine but I am getting errors about

   ....  is not allowed by Access-Control-Allow-Origin

This is very strange as both the grunt server that hosts my Angular.js site is on port 9000 and my rest service is on port 8678.

Anyway I found this

  https://gist.github.com/Vp3n/5340891

which explains how to enable CORS on the grunt server but my grunt file doesn't look the same... this is my current part of my grunt file

  connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: 'localhost'
      },
      livereload: {
        options: {
          middleware: function (connect) {
            return [
              lrSnippet,
              mountFolder(connect, '.tmp'),
              mountFolder(connect, yeomanConfig.app)
            ];
          }
        }
      },
      test: {
like image 366
Martin Avatar asked Dec 13 '25 23:12

Martin


1 Answers

I'm not sure what you mean by "my grunt file doesn't look the same", but you need to read the documentation of grunt-contrib-connect documentation which tells you that the middleware option accepts a function which should return an array of middlewares.

The referred gist is a simple middleware which allows CORS.

In your case it would look like:

connect: {
  options: {
    port: 9000,
    // Change this to '0.0.0.0' to access the server from outside.
    hostname: 'localhost'
  },
  livereload: {
    options: {
      middleware: function (connect) {
        return [
          lrSnippet,
          mountFolder(connect, '.tmp'),
          mountFolder(connect, yeomanConfig.app),
          function(req, res, next) {
            res.setHeader('Access-Control-Allow-Origin', '*');
            res.setHeader('Access-Control-Allow-Methods', '*');
            next();
          }
        ];
      }
    }
  },
  test: {
like image 109
Sindre Sorhus Avatar answered Dec 16 '25 21:12

Sindre Sorhus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!