Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
323 views
in Technique[技术] by (71.8m points)

node.js - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...