Why is the request event being fired twice

有些话、适合烂在心里 提交于 2021-02-11 12:33:55

问题


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);

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


回答1:


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.

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.



来源:https://stackoverflow.com/questions/53036889/why-is-the-request-event-being-fired-twice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!