简体   繁体   English

使用Express.js和Angular2进行CORS

[英]CORS with Express.js and Angular2

I'm trying to download a PLY file from my remote Express.js server to my Angular/Ionic app. 我正在尝试从远程Express.js服务器将PLY文件下载到Angular / Ionic应用程序。 I have my Ionic app hosted on Amazon AWS right now. 我现在将Ionic应用程序托管在Amazon AWS上。 Here's the Typescript from the Ionic app: 这是Ionic应用程序中的打字稿:

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

I have the following in my Express.js server: 我的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();
        }
    });

But I get the following error when requesting the PLY file: 但是当请求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.

This is really frustrating because I am using headers provided by the Express.js documentation to allow CORS. 这确实令人沮丧,因为我使用Express.js文档提供的标头来允许CORS。

Preflight -> Options -> https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS -> next() 预检->选项-> https://developer.mozilla.org/zh-CN/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');
});

Note: Move that stuff to the top of your configure function. 注意:将这些内容移至configure函数的顶部。


Or simple use express cors : 或简单使用表达cors

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

app.use(cors());

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM