node.js 如何将 CORS-Headers 添加到静态连接服务器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17124600/
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-09-02 14:48:11  来源:igfitidea点击:

How can I add CORS-Headers to a static connect server?

node.jscorsnode.js-connect

提问by afx

I am writing a little demo web server delivering static html,css and javascript. The server looks like

我正在编写一个小演示 Web 服务器,提供静态 html、css 和 javascript。服务器看起来像

(function () {
    "use strict";

    var http = require("http");
    var connect = require('connect');
    var app = connect()
        .use(connect.logger('dev'))
        .use(connect.static('home'));

    var server = http.createServer(app);
    server.listen(9999, function () {
        console.log('server is listening');
    });
})();

My client side javascript makes ajax calls to a different server. How can I add

我的客户端 javascript 对不同的服务器进行 ajax 调用。我怎样才能添加

Access-Control-Allow-Origin: http://example.com

to my server response, so that the client side javascript can do the ajax call?

到我的服务器响应,以便客户端 javascript 可以执行 ajax 调用?

采纳答案by Akshat Jiwan Sharma

Had a bit of trouble figuring this one out since expresshas spoiled me.

搞清楚这个有点麻烦,因为快递把我宠坏了。

Take a look at enable cors. Basically what you need to be doing is add Access-Control-Allow-Originto the domain you want to enable cors on. response.setHeadersis perfect for this task.

看看enable cors。基本上你需要做的是添加Access-Control-Allow-Origin到你想要启用 cors 的域。response.setHeaders非常适合此任务。

Another thing to note is that connect has no way to handle routes. If your app needs to have different routes then you will probably have to write logic for each of them and add res headers to the ones on which you want to enable cors. You can use req.urlfor it.

另一件需要注意的是 connect 没有办法处理路由。如果您的应用程序需要有不同的路由,那么您可能需要为每个路由编写逻辑,并将 res 标头添加到要启用 cors 的那些标头。你可以用req.url它。

var http = require("http");
var connect = require('connect');

var app = connect()

    .use(connect.logger('dev'))

    .use(connect.static('home'))

    .use(function(req, res){

    res.setHeader("Access-Control-Allow-Origin", "http://example.com");
    res.end('hello world\n');

 });

var server = http.createServer(app);

server.listen(9999, function () {

    console.log('server is listening');
});

This is the response I got in chrome dev tools

这是我在 chrome 开发工具中得到的响应

HTTP/1.1 200 OK
Access-Control-Allow-Origin: http://example.com
Date: Sat, 15 Jun 2013 16:01:59 GMT
Connection: keep-alive
Transfer-Encoding: chunked

回答by Chito Adinugraha

I hope this will help:

我希望这个能帮上忙:

//CORS middleware
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', config.allowedDomains);
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');

    next();
}

//...
app.configure(function() {

    app.use(allowCrossDomain);
    app.use(express.static(__dirname + '/public'));
});

More detail: How to allow CORS?

更多细节: 如何允许 CORS?

回答by Carl G

express.statictakes a configuration object. You can provide the property setHeadersand from that function you can set headers for the response:

express.static接受一个配置对象。您可以提供属性,setHeaders然后从该函数中可以为响应设置标头:

    app.use(express.static('public', {
      setHeaders: function setHeaders(res, path, stat) {
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET');
        res.header('Access-Control-Allow-Headers', 'Content-Type');
      }
    }))

The parameters to this function are:

这个函数的参数是:

  • res, the response object.
  • path, the file path that is being sent.
  • stat, the stat object of the file that is being sent.
  • res,响应对象。
  • path,正在发送的文件路径。
  • stat, 正在发送的文件的 stat 对象。

I wish that the request were available here so that I could conditionally set the CORS headers based upon the Originheader.

我希望请求在此处可用,以便我可以根据标头有条件地设置 CORS 标Origin头。

回答by vmathew

The easiest method, if you are using gulp would be to use gulp plugin called "gulp-connect" and "connect-modrewrite" and define a new gulptask to redirect a particular api. This is to make the apache act as a Proxy for the particular api, to bypass the pre-flight request, inorder to avoid CORs issue. I used the following gulp task to overcome this problem.

最简单的方法,如果您使用 gulp,将使用名为“gulp-connect”和“connect-modrewrite”的 gulp 插件并定义一个新的 gulptask 来重定向特定的 api。这是为了让 apache 充当特定 api 的代理,绕过飞行前请求,以避免 COR 问题。我使用以下 gulp 任务来解决这个问题。

var connect = require('gulp-connect'),
    modRewrite = require('connect-modrewrite');
/**
* Proxy Config
*/
gulp.task('connect', function () {
  connect.server({
    root: ['./.tmp', './.tmp/{folderLocations}', './src', './bower_components'],
    port: 9000,
    livereload: true,
    middleware: function (connect, opt) {
      return [
        modRewrite([
          '^/loginProxy/(.*)$ http://app.xyzdomain.com/service/login/auth/ [P]'
        ])
      ];
    }
  });
});