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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21581258/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:14:43  来源:igfitidea点击:

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

javascriptnode.jsangularjsgruntjsgrunt-contrib-connect

提问by shanti

I would like to allow access to cross origin calls which I need to be able to perform rest API calls to the server.

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

My connect grunt task is configured as follows:

我的连接 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();
        }
      ];
    }
  },
},

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.

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

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.

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

采纳答案by bpaul

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

      ];
    }
    },
    },

回答by ansorensen

Nod to bpaul, who set me on the path to correct answer. The format of a response to a similar questionwill work here.

向 bpaul 点点头,他让我走上了正确答案的道路。对类似问题的答复格式将在此处起作用。

Replace 'next' with middlewares, and push your anonymous function into the middleware array before returning it:

用中间件替换“next”,并在返回之前将匿名函数推送到中间件数组中:

middleware: function(connect, options, middlewares) {

    middlewares.unshift(function(req, res, next) {
        res.setHeader('Access-Control-Allow-Credentials', true);
        res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
        next();
    });

    return middlewares;
}

回答by wyu

Grunt connect comes with multiple middlewares, stored as functions in an array. When you set middleware by returning an array, you override the existing middleware responsible for serving your pages.

Grunt connect 带有多个中间件,以函数的形式存储在数组中。当您通过返回一个数组来设置中间件时,您将覆盖负责为您的页面提供服务的现有中间件。

Going off ansorensen's comment of the documentation, https://github.com/gruntjs/grunt-contrib-connect#middlewarethe relevant section being.

离开 ansorensen 对文档的评论,https://github.com/gruntjs/grunt-contrib-connect#middleware相关部分是。

options: {
    middleware: function(connect, options, middlewares) {
      // inject a custom middleware into the array of default middlewares
      middlewares.unshift(function(req, res, next) {
        if (req.url !== '/hello/world') return next();

        res.end('Hello, world from port #' + options.port + '!');
      });

      return middlewares;
    },
},

Middleware earlier in the array take effect before those later in the array.

数组中较早的中间件在数组中较晚的中间件之前生效。

So what you would want is

所以你想要的是

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, middlewares) {
            middlewares.unshift(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');

                return next();
            });

            return middlewares;
        }
    },
},

回答by Lalit Sachdeva

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.header('Access-Control-Allow-Credentials', true);
         res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
         res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
         next();
      }];
     }
   };

this will helps you in getting the get call Access-Control-Allow-Credentials

这将帮助您获得 get 调用 Access-Control-Allow-Credentials