【问题标题】:CORS and Access-Control-Allow-Methods in Express.js?Express.js 中的 CORS 和访问控制允许方法?
【发布时间】:2016-03-10 07:17:27
【问题描述】:

我有一个包含许多路线的快速应用程序:

app.get('foo/bar', function(res, res, next) { ... });
app.post('foo/bar', function(res, res, next) { ... });
app.get('another/one/path', function(res, res, next) { ... }));

我需要向这个应用程序发送跨域 AJAX 请求。所以,我需要在 OPTIONS 请求上发送正确的 Access-Control-Allow-Methods。例如,如果请求是 OPTIONS 'foo/bar',那么 Access-Control-Allow-Methods 标头应该等于 GET,POST。 我看到如果我在 Express 框架中发送 OPTIONS 请求,我已经在响应正文中获得了正确的方法列表。例如,如果我发送OPTIONS 'foo/bar',我会收到正文为GET,POST 的回复。现在,我也想在Access-Control-Allow-Methods 标头中发送GET,POST。我试图找到一个简单的解决方案来做到这一点。我不想添加选项路由,因为我的应用程序中已经有 200 多个路由。

【问题讨论】:

标签: node.js express cors


【解决方案1】:

最简单的解决方案是使用cors npm 包。

var express = require('express')
  , cors = require('cors')
  , app = express();

app.use(cors());

【讨论】:

    【解决方案2】:

    如果你想自己动手,这会让你开始。

    app.use(function(req, res, next) {
        var oneof = false;
        if (req.headers.origin) { //req.headers.origin.match(/whateverDomainYouWantToWhitelist/g) ) {
            res.header('Access-Control-Allow-Origin', req.headers.origin);
            oneof = true;
        }
        if (req.headers['access-control-request-method']) {
            res.header('Access-Control-Allow-Methods', req.headers['access-control-request-method']);
            oneof = true;
        }
        if (req.headers['access-control-request-headers']) {
            res.header('Access-Control-Allow-Headers', req.headers['access-control-request-headers']);
            oneof = true;
        }
        if (oneof) {
            res.header('Access-Control-Max-Age', 60 * 60 * 24 * 365);
        }
    
        // intercept OPTIONS method
        if (oneof && req.method == 'OPTIONS') {
            res.sendStatus(200);
        } else {
            next();
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2019-12-15
      • 1970-01-01
      • 2022-06-25
      • 2020-04-24
      • 2018-08-10
      • 2021-09-07
      • 2019-02-09
      • 2016-06-02
      • 2018-01-23
      相关资源
      最近更新 更多