与Express.js和Angular2的CORS

时间:2017-03-05 20:07:47

标签: javascript angularjs node.js express cors

我试图从我的远程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);");

我的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。

1 个答案:

答案 0 :(得分: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');
});

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

或简单使用express cors

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

app.use(cors());

app.get('/', function (req, res) {
    res.send('OK');
});