Detecting AJAX requests on NodeJS with Express

Ajaxnode.jsExpress

Ajax Problem Overview


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?

Ajax Solutions


Solution 1 - Ajax

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;
  ...
});

Solution 2 - Ajax

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...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmichaelView Question on Stackoverflow
Solution 1 - AjaxrobertklepView Answer on Stackoverflow
Solution 2 - AjaxkumarharshView Answer on Stackoverflow