繁体   English   中英

使用Connect / NodeJS时不需要多个请求

[英]Unwanted multiple requests while using Connect/NodeJS

我正在尝试使用Connect创建中间件,该中间件将Hello World显示到网页,并将其记录在控制台中。 我已经能够在浏览器中使用它,但是我注意到控制台记录了两次-使用curl时,它不会执行此操作。 我没有网站图标,Chrome中的所有扩展程序均已禁用。

这是我的代码...相当简单:

var connect = require('connect');

var app = connect();
app.use(function (req, res, next) {
    console.log('hello world');
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World');
});
app.listen(5000);

同样,在Chrome中打开http://localhost:5000后,这是终端中的输出:

hello world

hello world

为什么叫两次? 这正常吗?

您将收到两个请求,最有可能是铬检查图标。 添加console.log(req); 并检查对服务器的请求。

app.use(function (req, res, next) {
    console.log(req);
    console.log('hello world');
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World');
});

是。 当某人与服务器连接时,它将在服务器上发送消息。

那不正常。 如果仅刷新浏览器页面(Ctrl + R),则必须只看到一次“ hello world”。 在Chrome中打开开发人员工具 (菜单按钮-> 工具 -> 开发人员工具 ),然后切换到网络标签。 然后再次刷新浏览器页面,并检查浏览器发送的请求。

从文档:

response.end([数据],[编码])

该方法向服务器发送信号,指示所有响应头和主体已发送。 该服务器应认为此消息已完成。 必须在每个响应上调用方法response.end()。

如果指定了data ,则等效于调用response.write(data,encoding)后跟response.end()。

最后一行似乎是关键。 您将看到第一个控制台日志,然后相当于response.write。 缺少格式,我很抱歉,我在iPad上。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM