Why my node server processes the request twice?

前端 未结 2 860
遇见更好的自我
遇见更好的自我 2021-01-25 12:35

I have following simple node server.

const http = require(\'http\');

http.createServer(function(req, resp) {

    console.log(\"request arrived.\")
    resp.wri         


        
2条回答
  •  失恋的感觉
    2021-01-25 13:00

    It is most likely that the browser is requesting for the favicon.ico file. You can confirm that by printing the URL, like this

    console.log("request arrived for URL", req.url);
    

    When I tried this on my machine, with Chrome browser, I got

    request arrived for URL /
    request arrived for URL /favicon.ico
    

    If you want to avoid that, then you need to handle the favicon request specially. Probably, you can do something like this, as shown here

    if (req.url === '/favicon.ico') {
        resp.writeHead(200, {'Content-Type': 'image/x-icon'} );
        resp.end();
        console.log('favicon requested');
        return;
    }
    
    console.log("request arrived.")
    resp.writeHead(200, { 'Content-Type': 'application/json' });
    resp.end("Hello world!!");
    

提交回复
热议问题