【问题标题】:CORS with Express.js and Angular2带有 Express.js 和 Angular2 的 CORS
【发布时间】:2017-07-25 14:21:43
【问题描述】:

我正在尝试将 PLY 文件从远程 Express.js 服务器下载到我的 Angular/Ionic 应用程序。我现在将我的 Ionic 应用程序托管在 Amazon AWS 上。这是 Ionic 应用程序中的 Typescript:

//this.currentPlyFile encompasses entire URL
document.getElementById('entity').setAttribute("ply-model", "src: url(" + this.currentPlyFile + ".ply);");

我的 Express.js 服务器中有以下内容:

app.use(function(req, res, next) {
        res.header('Access-Control-Allow-Credentials', true);
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET,POST');
        res.header('Access-Control-Allow-Headers', 'appid, X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
        if ('OPTIONS' == req.method) {
            res.send(200);
        } else {
            next();
        }
    });

但在请求 PLY 文件时出现以下错误:

XMLHttpRequest cannot load "my url here" No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'my url here' is therefore not allowed access.

这真的很令人沮丧,因为我使用 Express.js 文档提供的标头来允许 CORS。

【问题讨论】:

    标签: javascript angularjs node.js express cors


    【解决方案1】:

    预检 -> 选项 -> https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS -> next()

    app.use(function(req, res, next) {
        res.header('Access-Control-Allow-Credentials', true);
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
        res.header('Access-Control-Allow-Headers', 'appid, X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
        next();
    });
    
    app.get('/', function (req, res) {
      res.send('OK');
    });
    

    注意:将这些内容移到配置函数的顶部。


    或者简单使用express cors:

    var express = require('express')
    var cors = require('cors')
    var app = express();
    
    app.use(cors());
    
    app.get('/', function (req, res) {
        res.send('OK');
    });
    

    【讨论】:

      猜你喜欢
      • 2012-07-28
      • 2016-12-28
      • 1970-01-01
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      • 2012-09-02
      • 2016-04-20
      • 2016-04-10
      相关资源
      最近更新 更多