【问题标题】:detect ajax request to normal request node js检测到正常请求节点js的ajax请求
【发布时间】:2014-05-29 18:23:30
【问题描述】:

你好 h 有下一个代码,我想知道如何在 ajax 请求和正常请求之间进行检测?没有快递。

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

【问题讨论】:

    标签: javascript jquery ajax node.js


    【解决方案1】:

    你可以检查request.headers是否包含HTTP_X_REQUESTED_WITH

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

    例子:

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

    【讨论】:

    • @user3493458 我添加了一个简单的示例。
    • 你可以只做if (request.xhr) { ... }
    • @soulchild 你不能,原生库中没有xhr 属性。
    • 嘿,抱歉,我在寻找 Express.js 的东西时遇到了这个。没有意识到这不是这里的混合部分。没关系。 ;-)
    • 显然 jQuery 是这个答案所必需的。我没有马上明白这一点。 stackoverflow.com/questions/12533435
    猜你喜欢
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 2017-08-19
    • 2012-06-02
    • 2015-09-15
    • 1970-01-01
    相关资源
    最近更新 更多