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