Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect ajax request to normal request node js

hello h have the next code and i like to know how to detect between an ajax request to a normal request? without express.

var http = require('http');
var fs = require('fs');
var path = require('path');
var url = require('url');

http.createServer(function (request, response) {
    console.log('request starting...');
console.log("request.url = " + request.url);
console.log("url = "+ url);

response.setHeader('content-Type','application/json');

var filePath = '.' + request.url;
if (filePath == './')
    filePath = './index.html';

var extname = path.extname(filePath);

var contentType = 'text/html';
switch (extname) 
{
    case '.js':
        contentType = 'text/javascript';
        break;
    case '.css':
        contentType = 'text/css';
        break;
}


fs.exists(filePath, function(exists) {

    if (exists) 
    {
        fs.readFile(filePath, function(error, content) {
            if (error) 
            {
                response.writeHead(500);
                response.end();
            }
            else 
            {         
                console.log("contentType = "+contentType);
                response.writeHead(200, { 'content-Type': contentType });
                response.end(content, 'utf-8');
            }
        });
    }
    else 
    {
        response.writeHead(404);
        response.end();
    }
});

}).listen(8081);
console.log('Server running at http://localhost:8081/');

in the client side i send an ajax request but i ask from the browser request to.

like image 469
liron Avatar asked Oct 01 '22 00:10

liron


1 Answers

You can check request.headers if it contains HTTP_X_REQUESTED_WITH.

If HTTP_X_REQUESTED_WITH has a value of XMLHttpRequest then it is an ajax request.

Example:

if (request.headers["x-requested-with"] == 'XMLHttpRequest') {
    //is ajax request
}
like image 166
Ben Fortune Avatar answered Oct 13 '22 09:10

Ben Fortune