I have simple node js code that returns a JSON string on UI if promise is successfully resolved, else it with show error on UI.
const server = require('http').createServer();
server.on('request', (request, response) => {
new Promise(function(resolve, reject) {
var jsonInput = '{"result":true, "count":42}';
resolve(JSON.parse(jsonInput));
}).then((data) => {
response.end(JSON.stringify(data));
}).catch((err) => {
response.end(String(err));
});
console.log('received a request');
});
server.listen(8000);
Why the 'received a request'
is printed twice? Does browser sends a second request automatically or my code is buggy?
Why the 'received a request' is printed twice?
Most likely, because your browser sent two requests. Chrome does that the first time you connect, for instance, sending first a request for the URL you actually asked for, and also a request for favicon.ico
. Look at request.url
to see what the requests are for.
For instance, if I take your code and put it in a file, and change the console.log
line to:
console.log('received a request: ' + request.url);
When I connect to http://localhost:8000/
, I see:
received a request: / received a request: /favicon.ico