javascript - Grunt 连接任务和中间件 Access-Control-Allow-Origin

标签 javascript node.js angularjs gruntjs grunt-contrib-connect

我想允许访问我需要能够对服务器执行 REST API 调用的跨源调用。

我的connect grunt任务配置如下:

    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();
        }
      ];
    }
  },
},

当我运行 grunt 服务器时,我得到 Cannot GET/。 在没有中间件配置的情况下,应用程序可以正常工作并且索引文件已正确加载。

你能指导我做错了什么或错过了什么吗?

关于我的 gruntfile 的更多细节是我正在使用 yeoman angular seed 应用程序作为我的应用程序的基础。

最佳答案

试试这样的:

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('.'))

      ];
    }
    },
    },

关于javascript - Grunt 连接任务和中间件 Access-Control-Allow-Origin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21581258/

相关文章:

javascript - 我可以在 React 中调用 componentWillMount 中的 API 吗?

Node.js module.exports 不导出整个对象

node.js - 使用 pg-promise 跳过更新列

javascript - 如何在 ES6/ES2015 中编写 Mongoose 模型

javascript - ionic 如何添加空白页作为应用程序的主页?

javascript - ng-grid展开和折叠行

javascript - 试图实现某种具有动态高度的可滚动容器

javascript - Jquery .on ('click' )奇怪的行为 - 选择具有相同类名的所有元素

javascript - 如何让多个图像在不同位置按顺序无限淡入和淡出(使用 abolute)?

javascript - 为什么 New Date() 总是返回 null?