Define ajax request for regular node js request

hello h has the following code, and I like to know how to determine between an ajax request for a regular request? without expression.

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/');

on the client side, I am sending an ajax request, but I am asking from a browser request.

+4
source share
1 answer

You can check request.headersif it contains HTTP_X_REQUESTED_WITH.

If HTTP_X_REQUESTED_WITHit matters XMLHttpRequest, then this is an ajax request.

Example:

if (request.headers["x-requested-with"] == 'XMLHttpRequest') {
    //is ajax request
}
+3
source

Source: https://habr.com/ru/post/1536592/


All Articles