How to detect AJAX request to normal request in Node.js ?
Ajax stands for asynchronous javascript and XML that is used to make dynamic requests to the server while the client is running.
There are two techniques to detect AJAX requests in Nodejs which are
- Check the headers of the request and if it contains HTTP_X_REQUESTED_WITH having a value of XMLHttpRequest then it is an ajax request.
- When you make an AJAX request, it adds ‘content type’:’application/json’ to the header of the request. So if the request contains the header then it is the AJAX
- If the referer header is different from the host header then it is an AJAX request
- If the sec-fetch-dest header is equal to empty then it is an AJAX request
Implementing the above last two approaches:
Example 1: If the referer header is different from the host header then it is an AJAX request:
- server.js: Create a file by the name server.js and paste the below code
Javascript
const http = require( 'http' ); const server = http.createServer((req, res) => { if (req.headers.host != req.headers.referer) { console.log( "It is the AJAX Request!" ); } }); server.listen(3000); |
- ajax.html: Create an HTML file and paste the below code:
Javascript
<!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <h1 style= "color:green" >GeeksforGeeks</h1> <h3>How to detect AJAX request to normal request Node.js?</h3> </body> <script> const xhr = new XMLHttpRequest(); xhr.send(); </script> </html> |
Execute the below command in the terminal:
node server.js
Open the ajax.html with the browser and observe the server.js output
Note: This code listens at port 3000 and prints a message when it gets an AJAX request
Output: In the output, I am executing the server.js and then running the ajax.html with HTTP protocol and detecting the AJAX
.gif)
Example 2: If the sec-fetch-dest header is equal to empty then it is an AJAX request
- server.js: Create a file by the name server.js and paste the below code
Javascript
const http = require( 'http' ); const server = http.createServer((req, res) => { if (req.headers[ 'sec-fetch-dest' ] == 'empty' ) { console.log( "It is the AJAX Request!" ); } }); server.listen(3000); |
- ajax.html: Create an HTML file and paste the below code
Javascript
<!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <h1 style= "color:green" >GeeksforGeeks</h1> <h3>How to detect AJAX request to normal request Node.js?</h3> </body> <script> const xhr = new XMLHttpRequest(); xhr.send(); </script> </html> |
Execute the below command in the terminal:
node server.js
Open the ajax.html with the browser and observe the server.js output
Note: This code listens at port 3000 and prints a message when it gets an AJAX request
Output: In the output, I am executing the server.js and then running the ajax.html with HTTP protocol and detecting the AJAX
.gif)
Please Login to comment...