0

I have just started out learning Node js. I can't understand why in output.txt I am seeing "2020 Septemberundefined undefined" in output.txt when I call:

http://localhost/?month=September&year=2020

I am expecting to see just "2020 September" in output.txt.

var http = require('http');
var url = require('url');
var fs = require('fs');

//create a server object:
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  var q = url.parse(req.url, true).query;
  var txt = q.year + " " + q.month;
  fs.appendFile('output.txt', txt, function (err) {
        // nothing
  });
  res.end(); //end the respons
}).listen(8080); //the server object listens on port 8080

2 Answers 2

1

The favorite icon. Add console.log(req.url). You will see that the browser makes two requests.

Sign up to request clarification or add additional context in comments.

Comments

0

Browser is sending requests for http://localhost:8080/favicon.ico, behind the scenes.

So whenever you hit http://localhost:8080/?month=September&year=2020, node write "2020 September" to output.txt file, meanwhile browser hit favicon.ico request then node write again "undefined undefined" in output.txt file.

if you want to skip favicon.ico request,

var http = require('http');
var url = require('url');
var fs = require('fs');

//create a server object:
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    if (req.url != '/favicon.ico') {
      var q = url.parse(req.url, true).query;
      var txt = q.year + " " + q.month;
      fs.appendFile('output.txt', txt, function (err) {
            // nothing
      });
    }
  res.end(); //end the respons
}).listen(8080);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.