Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting AJAX requests on NodeJS with Express

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?

like image 751
michael Avatar asked Apr 11 '13 09:04

michael


People also ask

How to fetch data from MySQL database in Node JS app?

Then add the following code into it: Create ajax get request for fetch data from mysql database in node js app: Create ajax post request send data into from mysql database and display response data into html page in node js app: Create get and post request routes; so visit routes open server.js file; Then add the following routes into it:

How do I set up a project using express node express?

Navigate to where you’d like your project to reside, then run the following command: $ express node-express-ajax-craigslist CD into the newly created directory and install the node modules: $ cd node-express-ajax-craigslist $ npm install Aside for the installed node modules/dependencies, your project structure should look like this:

How do I make an Ajax request in JavaScript?

Open main.jsand look at the following code: $.get('/searching',parameters,function(data){$('#results').html(data); This is the actualAJAX request. As I stated before, we pass the parameters(which is an object) to the server side.

How do I make an Ajax request in Redux?

Main.js (client-side) redux Open main.jsand look at the following code: $.get('/searching',parameters,function(data){$('#results').html(data); This is the actualAJAX request. As I stated before, we pass the parameters(which is an object) to the server side.


2 Answers

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;   ... }); 
like image 142
robertklep Avatar answered Oct 10 '22 20:10

robertklep


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

like image 21
kumarharsh Avatar answered Oct 10 '22 20:10

kumarharsh