I'm using NodeJS with Express. How can I tell the difference between an ordinary browser request and an AJAX request? I know I could check the request headers but does Node/Exprsss expose this information?
-
3I always console.log() the req object.This way I can check a number of useful objects that it contains. – Akshat Jiwan Sharma Apr 11 '13 at 10:13
-
1@AkshatJiwanSharma I have started doing this as well, it's crazy to think I didn't use this technique before! – sharkman Jul 18 '13 at 18:48
Most frameworks set the X-Requested-With
header to XMLHttpRequest
, for which Express has a test:
app.get('/path', function(req, res) {
var isAjaxRequest = req.xhr;
...
});
-
14
In case the req.xhr
is not set, say in frameworks such as Angularjs, where it was removed, then you should also check whether the header can accept a JSON response (or XML, or whatever your XHR sends as a response instead of HTML).
if (req.xhr || req.headers.accept.indexOf('json') > -1) {
// send your xhr response here
} else {
// send your normal response here
}
Of course, you'll have to tweak the second part a little to match your usecase, but this should be a more complete answer.
Ideally, the angular team should not have removed it, but should have actually found a better solution for the CORS' pre-flight problem, but that's how it rests now...
-
I also like the solution suggested in the link: just add the
X-Requested-With
back to$httpProvider
if you depend on this functionality. – robertklep Feb 16 '15 at 15:49 -
Yup, that's one way, but just in case other frameworks are found with equally lazy devs, then it's for them :) – kumarharsh Feb 17 '15 at 7:10
-
For an API for internal use, I do believe adding the header back is the proper thing to do. If your API is going to be used by others, though luck indeed. Although you could require developers to add this header too: developers should be smart enough to be able to do that. – Stephan Bijzitter Jan 22 '16 at 15:24
-
9You can make
req.xhr
work for AngularJS requests by adding this to your angular app config:$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
– steampowered Apr 20 '16 at 22:19 -
4@kumar_harsh he did not provide the full line of code, but I did. so I added some information nobody had yet provided. – steampowered Apr 24 '16 at 18:24