检测到正常请求节点js的ajax请求

你好有下一个代码,我想知道如何检测一个Ajax请求到一个正常的请求? 没有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/'); 

在客户端我发送一个Ajax请求,但我要求从浏览器请求。

如果它包含HTTP_X_REQUESTED_WITH你可以检查request.headers

如果HTTP_X_REQUESTED_WITH具有XMLHttpRequest的值,那么它是一个ajax请求。

例:

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