与Express.js和Angular2的CORS

Pet*_*ter 1 javascript node.js cors express angularjs

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

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

我的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();
        }
    });
Run Code Online (Sandbox Code Playgroud)

但是在请求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.
Run Code Online (Sandbox Code Playgroud)

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

lin*_*lin 5

预检 - >选项 - > 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');
});
Run Code Online (Sandbox Code Playgroud)

注意:将这些内容移动到配置功能的顶部.


或简单使用快递:

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

app.use(cors());

app.get('/', function (req, res) {
    res.send('OK');
});
Run Code Online (Sandbox Code Playgroud)