Peter
Peter

Reputation: 328

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. I have my Ionic app hosted on Amazon AWS right now. Here's the Typescript from the Ionic app:

//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:

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:

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.

Upvotes: 1

Views: 2815

Answers (1)

lin
lin

Reputation: 18402

Preflight -> Options -> 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');
});

Note: Move that stuff to the top of your configure function.


Or simple use express cors:

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

app.use(cors());

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

Upvotes: 5

Related Questions