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?
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.
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
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With