2014-04-15 16 views
4

hello h有下一个代码,我想知道如何检测ajax请求与正常请求之间的关系?没有明示。检测ajax请求到正常请求节点js

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请求,但我要求从浏览器请求。

回答

3

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

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

例子:

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

可你莫比显示我如何做到这一点...? – liron

+0

@ user3493458我已经添加了一个快速示例。 –

+0

你可能只需要做'if(request.xhr){...}'。 –