I've an ExpressJS application exposing some data via REST. When I access the REST interface form the same origin or by using curl, everything is fine and my custom http header is forwareded to my route.
But when I try to access the REST interface from another origin my headers are removed.
The expressjs configuration looks like this
app.use(express.bodyParser());
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET');
res.header('Access-Control-Allow-Headers', 'Accept');
if ('OPTIONS' == req.method) {
res.send(200);
}
else {
next();
}
};
app.all('/',allowCrossDomain);
app.get('/foo', function(req,res){
console.dir(req.headers);
});
I try to access the api using the following JS code
var properties = {
url: 'http://localhost:3001/foo?callback=?,
type: 'GET',
dataType: 'jsonp',
headers: { "x-foo" : "FooBar"}
};
$.ajax(properties).done(onSuccess).fail(function(r, s, e) {
console.log(e);
});
On the server-side the custom header x-foo is not part of req.headers. If I use the following curl command my header exists
curl -H "x-foo: FooBar" -G http://localhost:3001/foo
Unfortunately I'm not able to find any solution to get this up and running.
Your line
app.all('/', ...);
does not do what you might think it does. It does NOT handle all incoming requests. It just handles all incoming requests for /, regardless of the verb being used. Hence, all means all verbs, not all routes. See its documentation for details.
So, when you try to access /foo using the $.ajax call, your CORS middleware is not triggered. Perhaps this may be the reason. At least this could explain why it works from localhost and curl, but not from within the browser using a different domain.
Hope this helps.
PS: I'd recommend not to write your own CORS middleware, but use an existing one. I've made quite good experiences with node-cors.