Nodejs 求助,get请求为什么发出了两次

Nodejs 求助,get请求为什么发出了两次

var http = require(‘http’),
q = require(‘querystring’);

http.createServer(function (req, res) {

	var options = {
		host : '192.168.1.2',
		port : 7379,
		path : '/INCR/soscount',
		method : 'get'
	};

//服务端发出请求get
http.get(options,function(response){
	res.writeHead(200, {'Content-Type': 'text/plain'});
	var pageData = "";
	response.setEncoding('utf8');
	//接受数据,保存
	response.on('data', function (chunk) {
	  pageData += chunk;
	});

	//数据接收完毕, 输出到客户端
	response.on('end', function(){
	  res.write(pageData);
	  res.end();
	});

});

}).listen(4000); console.log(“httpServer is listening at port 4000”)

想用nodejs发起一个webredis的测试, 直接浏览器访问 http://192.168.1.2:7379/INCR/soscount 的时候 每次访问 数字会+1 但是如果通过nodejs 访问,每次访问数字会+2 这是为什么呢。。。

4 回复

标题:Nodejs 求助,get请求为什么发出了两次

内容:

您遇到的问题是因为在 http.createServer 中,每当有一个新的请求到达时,就会执行一次创建服务器的回调函数。这意味着在您的代码中,每次有一个新的请求到达时,都会创建一个新的 http.get 请求。因此,如果您的浏览器访问了该服务器,那么每次都会触发两次 http.get 请求。

示例代码分析

var http = require('http'),
    q = require('querystring');

http.createServer(function (req, res) {
    var options = {
        host : '192.168.1.2',
        port : 7379,
        path : '/INCR/soscount',
        method : 'get'
    };

    // 服务端发出请求get
    http.get(options, function(response){
        res.writeHead(200, {'Content-Type': 'text/plain'});
        var pageData = "";
        response.setEncoding('utf8');
        
        // 接受数据, 保存
        response.on('data', function (chunk) {
            pageData += chunk;
        });

        // 数据接收完毕, 输出到客户端
        response.on('end', function(){
            res.write(pageData);
            res.end();
        });
    });
}).listen(4000);

console.log("httpServer is listening at port 4000");

问题解释

在这个代码片段中,http.createServer 回调函数内部创建了一个 http.get 请求。当您访问 http://localhost:4000 时,http.createServer 回调函数会被调用两次(因为这是两个独立的请求),每次都会创建一个新的 http.get 请求。因此,实际上会有两个 http.get 请求被发送到目标地址 http://192.168.1.2:7379/INCR/soscount,导致计数值增加了两次。

解决方案

为了确保 http.get 请求只发送一次,您可以将 http.get 请求移动到外部,并在需要时调用它。例如,可以使用一个单独的函数来处理 http.get 请求,然后在需要时调用该函数。

function makeGetRequest(callback) {
    var options = {
        host : '192.168.1.2',
        port : 7379,
        path : '/INCR/soscount',
        method : 'get'
    };

    http.get(options, function(response){
        var pageData = "";
        response.setEncoding('utf8');
        response.on('data', function (chunk) {
            pageData += chunk;
        });

        response.on('end', function(){
            callback(null, pageData);
        });
    }).on('error', function(e) {
        callback(e);
    });
}

http.createServer(function (req, res) {
    makeGetRequest(function(err, data) {
        if (err) {
            res.writeHead(500, {'Content-Type': 'text/plain'});
            res.end('Error occurred.');
        } else {
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end(data);
        }
    });
}).listen(4000);

console.log("httpServer is listening at port 4000");

这样,makeGetRequest 函数只会在需要时被调用一次,从而避免重复请求的问题。


因为多访问了一次"/favicon.ico"

明白了,要路由一下,感谢

你的问题可能是因为在 Node.js 中,当 HTTP 请求被成功响应后,但客户端没有正确地关闭连接,这可能会导致请求被重试。然而,在你的代码中,更有可能的原因是在请求处理函数中,http.get 被放置在了服务器请求处理函数中,这意味着每当客户端访问你的服务器时,都会触发一次 http.get 请求。

示例代码

为了更好地理解,你可以修改代码,将 http.get 放在一个单独的函数中,并确保只调用一次。这里是一个改进的例子:

var http = require('http');
var querystring = require('querystring');

function makeGetRequest(callback) {
    var options = {
        host: '192.168.1.2',
        port: 7379,
        path: '/INCR/soscount',
        method: 'GET'
    };

    // 发起 get 请求
    var req = http.get(options, function (response) {
        var pageData = '';
        response.setEncoding('utf8');

        // 接收数据并保存
        response.on('data', function (chunk) {
            pageData += chunk;
        });

        // 数据接收完毕,执行回调函数并将结果传递回去
        response.on('end', function () {
            callback(null, pageData);  // 在回调中返回结果
        });
    });

    req.on('error', function (e) {
        console.error(`Problem with request: ${e.message}`);
        callback(e, null);  // 如果出错也传递给回调
    });
}

http.createServer(function (req, res) {
    // 只调用一次 makeGetRequest 函数
    makeGetRequest(function (err, data) {
        if (err) {
            res.writeHead(500, {'Content-Type': 'text/plain'});
            res.end('Error occurred.');
        } else {
            res.writeHead(200, {'Content-Type': 'text/plain'});
            res.end(data);
        }
    });
}).listen(4000);

console.log('httpServer is listening at port 4000');

在这个改进后的代码中,makeGetRequest 函数被设计为一个独立的函数,用于发起 GET 请求。这个函数被放在服务器请求处理函数外部,并且在每次客户端访问时只调用一次。这样可以避免重复请求的问题。

回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!