Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js express: How can I know if a request is an AJAX request?

Let's say I have a small piece of code:

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

app.get('/', function(req, res){
  //I want to acccess 'req' and get info whether it's an AJAX call
});

app.listen(3000);

When I go inside the app.get(..) function, I want to know if the get request sent is an AJAX call. What is the field in the object 'req' that can tell me this?

like image 265
CrazySynthax Avatar asked Dec 15 '22 01:12

CrazySynthax


2 Answers

The header X-Requested-With: XMLHttpRequest HTTP header is not automatically added to an AJAX request, either with fetch or with the old-fashioned use of the XMLHttpRequest object. It is often added by client libraries such as jQuery.

If the header is present, it is represented in Express by request.xhr.

If you want to add it to the request (the simplest solution to this problem) you can add it as a custom header with fetch:

fetch(url, {
    headers: {
        "X-Requested-With": "XMLHttpRequest"
    }
});

This will now be reflected in req.xhr.

A better solution is to set the Accept header to a sensible value. If you want JSON to be returned, set Accept to application/json:

fetch(url, {
    headers: {
        "Accept": "application/json"
    }
});

You can then test for this with req.accepts:

switch (req.accepts(['html', 'json'])) { //possible response types, in order of preference
    case 'html':
        // respond with HTML
        break;
    case 'json':
        // respond with JSON
        break;
    default:
        // if the application requested something we can't support
        res.status(400).send('Bad Request');
        return;
}

This is much more powerful than the req.xhr approach.

like image 108
lonesomeday Avatar answered Jan 29 '23 16:01

lonesomeday


app.get('/', function(req, res){
  //I want to acccess 'req' and get info whether it's an AJAX call
  if(req.xhr){
     //the request is ajax call
  }
})
like image 27
Ebrahim Pasbani Avatar answered Jan 29 '23 16:01

Ebrahim Pasbani