Grunt Server:不支持CORS,给出错误

Mar*_*tin 2 cors angularjs gruntjs

我有一个服务器设置,一切都很顺利,但我得到的错误

   ....  is not allowed by Access-Control-Allow-Origin
Run Code Online (Sandbox Code Playgroud)

这很奇怪,因为托管我的angularjs站点的grunt服务器在端口9000上,而我的其余服务在端口8678上.

无论如何我发现了这个

  https://gist.github.com/Vp3n/5340891
Run Code Online (Sandbox Code Playgroud)

这解释了如何在grunt服务器上启用CORS但是我的grunt文件看起来不一样......这是我当前的grunt文件的一部分

  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: {
Run Code Online (Sandbox Code Playgroud)

任何帮助真的很感激

提前致谢

Sin*_*hus 9

我不确定你的意思是"我的grunt文件看起来不一样",但你需要阅读grunt-contrib-connect文档的文档,该文档告诉你该middleware选项接受一个函数,该函数应返回一个数组中间件.

引用的要点是一个允许CORS的简单中间件.

在你的情况下,它看起来像:

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: {
Run Code Online (Sandbox Code Playgroud)