【问题标题】:Grunt Server: Not supporting CORS, gives errorGrunt 服务器:不支持 CORS,出现错误
【发布时间】:2013-06-18 20:27:45
【问题描述】:

我有一个服务器设置,一切正常,但我收到了关于

的错误
   ....  is not allowed by Access-Control-Allow-Origin

这很奇怪,因为托管我的 Angular.js 站点的 grunt 服务器都在端口 9000 上,而我的 rest 服务在端口 8678 上。

反正我找到了这个

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

这解释了如何在 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: {

【问题讨论】:

    标签: angularjs cors gruntjs


    【解决方案1】:

    我不确定您所说的“我的 grunt 文件看起来不一样”是什么意思,但是您需要阅读 grunt-contrib-connect 文档的文档,该文档告诉您 middleware 选项接受一个函数它应该返回一个中间件数组。

    引用的 gist 是一个允许 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: {
    

    【讨论】:

    • 我也遇到了同样的问题,但这并不能解决?你能看看吗? stackoverflow.com/questions/19391711/…
    • lrSnippet 参数是如何定义的?你能提供整个 gruntfile 吗?
    • @paweloque 它是 grunt-connect 的旧符号,它已更改为 grunt-contrib-connect
    【解决方案2】:

    我面临同样的问题,无法让 Grunt 正常运行。这是来自 Gruntfile.js 的相应片段:

    connect: {
      options: {
        port: 9000,
        // Change this to '0.0.0.0' to access the server from outside.
        hostname: '0.0.0.0',
        livereload: 35729
      },
      livereload: {
        options: {
          open: true,
          base: [
            '.tmp',
            '<%= yeoman.app %>'
          ]
        }
      },
    

    用中间件更新它以将Access-Control-Allow-... Headers 设置为* 的正确方法是什么?

    【讨论】:

    • 我也遇到了同样的问题,你能解决吗?
    • 我不确定它是否会对您有所帮助,但我遇到了同样的问题,而且它似乎与导致 CORS 问题的前端应用程序无关。这是不允许 CORS 的后端(用 python/django 编写的 API)。所以我的解决方案是为后端启用 CORS。不需要对 grunt 进行任何更改。
    • 是的,我锻炼了,它不是咕噜声。我必须配置 $http 请求以允许 JSONP。
    猜你喜欢
    • 2011-06-24
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 2020-01-24
    • 1970-01-01
    • 2012-01-14
    • 2020-04-09
    • 1970-01-01
    相关资源
    最近更新 更多