I would like to implement a very simple CORS scenario. Here's my server written in node.js/express:
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var app = express();
var router = express.Router();
router.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'X-Test-Header');
next();
});
router.get('/', function(req, res, next) {
console.log('Request arrived');
res.json({data: 'hello'});
next();
});
app.set('port', process.env.PORT || 3000);
app.use(morgan('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride());
app.use('/', router);
app.listen(app.get('port'), function(){
console.log('Express is up on ' + app.get('port'));
});
To complement this I have a very simple AngularJS file as well:
var app = angular.module('myapp', []);
app.controller('MyCtrl', function($scope, $http) {
var config = {
headers: {
'X-Test-Header': 'Test Header Data'
}
};
$scope.test = 'Hello World';
$scope.getData = function () {
console.log('clicked');
$http.get('http://localhost:3000/', config).
success(function (data, status) {
console.log('Status: ', status);
console.log('Data: ', data);
}).
error(function (data, status) {
console.log('Status: ', status);
console.log('Data: ', data || 'Request failed');
});
}
});
The output in my console for the node/express app is simply:
Express server listening on port 3000
OPTIONS / 200 4.767 ms - 3
Request arrived
GET / 200 2.572 ms - 16
And in the browser's console I see: 'clicked'.
On the network tab I see that there were two request made once I have clicked the button - one OPTIONS that returned a 200 OK, and a GET method which is pending forever.

So my question is of course, why am I experiencing this behaviour? I tried digging and read quite a few articles and tried their suggestions but none of them worked.
Interestingly enough the following has fixed the issue:
router.all('/', function(req, res, next) {
console.log('Request arrived');
res.type('application/json');
res.json({datax: 'hello'});
next();
});
notice the diff --> router.get('/') vs router.all('/'). I'm a bit baffled why this is happening though.
UPDATE Here's a much better code that I put together, now that I understand this a bit more ...
app.route('/')
.options(function (req, res, next) {
res.status(200).end();
next();
})
.get(function (req, res) {
res.json({data: 'hello'});
});
And here's a quick writeup about my findings: http://tamas.io/node-jsexpress-cors-implementation/