liron
liron

Reputation: 87

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.

Upvotes: 5

Views: 4221

Answers (2)

Nai
Nai

Reputation: 71

I came across this question and I know it's old but in case someone needs the answer and the idea behind it.

Usually, on the client side, when you make an AJAX request you add a key and value that describe the content i.e: 'content type':'application/json'

So simply, on the server side, you can test the header if it contains application/json as the content type then you are safe to say it's an ajax request.

req.headers['content-type'] == 'application/json'

Upvotes: 0

Ben Fortune
Ben Fortune

Reputation: 32127

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
}

Upvotes: 4

Related Questions