为什么每次请求都会调用两次回调函数? [英] Why the callback function gets called twice for each request?

查看:167
本文介绍了为什么每次请求都会调用两次回调函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

伙计们,我是 node js 的新手,这种行为对我来说很奇怪!在下面的代码片段中,

Guys I am new to node js and this behavior is strange to me! In the code snippet below,

'use strict';
var http = require('http');
var numberOfRequests = 0;
http.createServer(function (request, responce) {
    console.log('Request number ' + numberOfRequests + ' received!');
    responce.writeHead(200);
    responce.write("Here is responce to your request..");
    responce.end();
    numberOfRequests++;
}
).listen(8080);
console.log('listening ...');

对于每个

localhost:8080 

调用 Chrome,应用程序在控制台上写入两次?e.i对于单个 8080 呼叫,它会打印出:

call at Chrome, the app writes twice onto console? e.i for a single 8080 call, it prints out:

Request number 0 received!
Request number 1 received!

我正在使用 Visual Studio 运行此节点 js 应用程序.

I am using Visual studio to run this node js app.

推荐答案

通常,当您看到每个页面请求有两个请求时,一个针对所需页面,一个针对网站的 favicon.这是大多数浏览器所做的,除非页面中有元标记告诉浏览器不要请求图标资源.如果您在处理程序中执行此操作:

Usually, when you see two requests for each page request, one is for the desired page and one is for the favicon for the website. This is what most browsers do unless there is meta tag in the page that tells the browser not to request a favicon resource. If you do this in your handler:

console.log(request.url)

这可能会告诉你发生了什么.通常,您不希望拥有一个从不查看请求的资源的 Web 服务器.如果您的逻辑基于被请求的特定资源,例如 /,那么您将很容易忽略其他类型的请求,例如图标.

That will likely show you what's going on. In general, you don't want to have a web server where you never look at what resource is being requested. If you based your logic on a specific resource being requested such as /, then you would easily be able to ignore other types of requests such as the favicon.

这篇关于为什么每次请求都会调用两次回调函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆