与Express.js和Angular2的CORS

我试图从我的远程Express.js服务器下载一个PLY文件到我的Angular / Ionic应用程序。 我现在在Amazon AWS上托pipe我的Ionic应用程序。 这是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。

预检 – >选项 – > 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'); }); 

注意:将这些东西移到configuration函数的顶部。


或者简单的使用express cors :

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