Search code examples
node.jshttp2

Why is the request event being fired twice


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


Solution

  • 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.