Rest API with LocomotiveJs using CORS. Works on local machine but not on Amazon or Heroku

I did a REST api using LocomotiveJs and now I'm trying to enable CORS on it. I added the following code to my "all" environment (config/environments/all.js).

this.use(function crossOrigin(req,res,next){
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With,Authentication");
    res.header("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");

    return next();
});

It works on my local machine but when I deploy it to Heroku or AWS I got a 404 Http Error when the client sends the OPTIONS command.

In order to isolate the problem, I developed a simple Express app, with the following code:

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

app.all('*', function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "X-Requested-With,Authentication");
  next();
 });

app.get('/test', function(req, res){
    res.set('Content-Type', 'application/json');
    res.send({ 'Hello' : 'World' });
});

var port = process.env.PORT || 5000;

app.listen(port);
console.log('Listening on port ' + port);

And this code worked when deployed to Heroku!

Do you guys have any opinion on why it worked on my local machine and didn't work on the servers?

有帮助吗?

解决方案

I found a solution:

Now I'm using this connect middleware: https://github.com/troygoode/node-cors

Then I just changed my all.js file adding the following line:

this.use(cors());

I deployed it on Heroku and works now.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top