为什么请求事件被触发两次 [英] Why is the request event being fired twice

查看:103
本文介绍了为什么请求事件被触发两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一台看起来像这样的服务器:

I have a server which looks like this:

const http2 = require('http2');
const {
    HTTP2_HEADER_METHOD,
    HTTP2_HEADER_PATH,
    HTTP2_HEADER_STATUS,
    HTTP2_HEADER_CONTENT_TYPE
  } = http2.constants;

const fs = require('fs');

const server = http2.createSecureServer({
  key: fs.readFileSync('./ssl/localhost-privkey.pem'),
  cert: fs.readFileSync('./ssl/localhost-cert.pem')
});


server.on('error', (err) => {
    console.error(err);
});

server.on('stream', (stream, headers,flags) => {
  stream.respond({
    'content-type': 'text/html',
    [HTTP2_HEADER_STATUS]: 200,
    [HTTP2_HEADER_CONTENT_TYPE]: 'text/plain'
  });
  stream.end('<h1>Hello World 2</h1>');
});



server.on('request', (msg) => {
  /* THIS IS BEING FIRED TWICE*/
   console.log('request:' + JSON.stringify(msg) );
});


server.on('session', (msg) => {
 /* THIS IS ALSO BEING FIRED TWICE*/
    console.log('session:' + JSON.stringify(msg) );
});

 server.listen(8443);

从我的浏览器中,输入URL https://myserver:8443 .在我的服务器上,我可以看到两次会话事件都是控制台日志.为什么由于我只提出一个请求而发生这种情况?同样,每次刷新页面时,都会触发两次请求事件,而不是一次.我正在使用nodejs 11.0.0

From my browser I type into the url https://myserver:8443. On my server I can see the session event is consoled log twice. Why is this happening since I am only making one request? As well everytime I refresh the page the request event is being fired twice instead of only once. I am using nodejs 11.0.0

推荐答案

您应该使用 console.log(msg.url)记录所请求的URL.您可能会发现其中一个请求是针对favicon.ico的,因为这是浏览器在尚未为特定域缓存favicon时会请求的内容.

You should log the URL that is being requested with console.log(msg.url). You will likely find that one of the requests is for the favicon.ico as this is something that a browser will request when it doesn't already have a favicon cached for a particular domain.

Web服务器的所有请求都必须查看请求的实际资源,并根据请求的确切资源做出适当的响应.

All requests of a web server have to look at the actual resource being requested and respond appropriately based on the exact resource being requested.

这篇关于为什么请求事件被触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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