node js console code is executed two times - node.js

I am executing following simple node js code
var http = require('http');
http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type':'text/plain'});
res.end('Hello Node JS');
console.log('printing the message');
}).listen(8080);
After executing the command node sample.js and
hitting the url on browser http://localhost:8080/
I am getting the console log statement twice on the command prompt as printing the message
Any Suggestions
EDIT:
Interestingly After checking on other browsers i.e. Firefox, IE no favicon.ico request is made on network tab and console message is printed only once.
As I understood, using express module is better option to handle requests in a typical web application

check the Network area of your browser's developer console to find out what requests are being made. I imagine you will see two:
GET /
GET /favicon.ico
your HTTP server is coded to respond to all requests by printing to console; so if you see two requests, you get two console messages.

Related

Why the callback function gets called twice for each request?

Guys I am new to node js and this behavior is strange to me!
In the code snippet below,
'use strict';
var http = require('http');
var numberOfRequests = 0;
http.createServer(function (request, responce) {
console.log('Request number ' + numberOfRequests + ' received!');
responce.writeHead(200);
responce.write("Here is responce to your request..");
responce.end();
numberOfRequests++;
}
).listen(8080);
console.log('listening ...');
for each
localhost:8080
call at Chrome, the app writes twice onto console? e.i
for a single 8080 call, it prints out:
Request number 0 received!
Request number 1 received!
I am using Visual studio to run this node js app.
Usually, when you see two requests for each page request, one is for the desired page and one is for the favicon for the website. This is what most browsers do unless there is meta tag in the page that tells the browser not to request a favicon resource. If you do this in your handler:
console.log(request.url)
That will likely show you what's going on. In general, you don't want to have a web server where you never look at what resource is being requested. If you based your logic on a specific resource being requested such as /, then you would easily be able to ignore other types of requests such as the favicon.
Run curl <hostname:port> to make a single request. This proves it's the browser making multiple.

Node Http server - request received twice

I am learning Node.js and I have created this simple http server.
var http = require('http');
var server = http.createServer(function(req,res){
console.log('request accepted');
res.end();
});
server.listen(3000,function(){
console.log("Server listening on port #3000");
});
It is working fine but when I visit http://localhost:3000/ the console logs request accepted thing twice. In short, if I'm understanding correctly, the request is received twice.
Is it a correct behavior or am I doing something wrong here?
Your browser makes two HTTP requests. One for the page at / and the other for /favicon.ico.
You can prove this by inspecting req.url.
you can try to put your favicon as a data64 string so you will save that request, anyway some browsers could make that request anyway.

Getting proxy error when using "gulp serve" when API returns 204 with no content

I am using Gulp to develop an Angular application generated by Yeoman's gulp-angular generator. I have configured it to proxy requests to /api to another port, the port my API is listening on. That port is actually forwarded via an SSH tunnel to an external server.
Here is the config generated by Yeoman that I have edited for my own API:
gulp/server.js
'use strict';
var gulp = require('gulp');
var browserSync = require('browser-sync');
var httpProxy = require('http-proxy');
/* This configuration allow you to configure browser sync to proxy your backend */
var proxyTarget = 'http://localhost:3434/api'; // The location of your backend
var proxyApiPrefix = 'api'; // The element in the URL which differentiate between API request and static file request
var proxy = httpProxy.createProxyServer({
target: proxyTarget
});
function proxyMiddleware(req, res, next) {
if (req.url.indexOf(proxyApiPrefix) !== -1) {
proxy.web(req, res);
} else {
next();
}
// ...rest of config truncated
stdout
[BS] Watching files...
/Users/jason/dev/web/node_modules/http-proxy/lib/http-proxy/index.js:114
throw err;
^
Error: Parse Error
at Socket.socketOnData (http.js:1583:20)
at TCP.onread (net.js:527:27)
I get the above error when my application attempts to hit a particular API url which sends back a response of 204, no content.
url structure: POST /api/resource/delete
(API doesn't support actual DELETE http method so we POST to this endpoint)
Response: 204 No Content
The API is also in development and is being served via the built in PHP web server. What the server is telling us is that the client (aka Node in this case because it is the proxy) is hanging up before PHP can send the response.
I thought perhaps it was just choking on the fact that there was no content. So, we created a second endpoint that also returned 204 No Content and it seemed to work fine. But, to be fair, this issue appears to be intermittent - it works sometimes and sometimes it does not. It's very confusing.
As far as we can tell, it only happens on this delete URL, however. I am pretty new to Node and am having a very hard time figuring out what the issue is or where to look. Does anyone have any clues or has anyone seen this before?
It turns out that the developer of the API was sending me content along with his 204 when he shouldn't have been - some debug code left in. The HTTP parser that node-proxy uses was then reading that content from the buffer at the beginning of the subsequent request and then throwing an error because it wasn't seeing a properly formed HTTP request - since the first thing in the buffer was a PHP var_dump.
As it happens, my front end app did the delete call and then refreshes another object via the GET request. They happen so fast that it seemed like the DELETE call killed the gulp server, when it was actually the GET command afterwards.
The http-proxy module for node explicitly does not do error handling, leaving the onus on the end user. If you don't handle an error, it bubbles up into an uncaught exception and will cause the application to close, as I was seeing.
So, the fix was simply:
gulp/server.js
var proxy = httpProxy.createProxyServer({
target: proxyTarget
}).on('error', function(e) {
console.log(JSON.stringify(e, null, ' '))
});
The console will now log all proxy errors, but the process won't die and subsequent requests will continue to be served as expected.
For the error in question, the console output is:
{
"bytesParsed": 191,
"code": "HPE_INVALID_CONSTANT"
}
Additionally, we've fixed the API to honor its 204 and actually, you know, not send content.

Routes with parameters gets called twice?

I am creating a NodeJS web application via ExpressJS. I have the following two routes (among others):
app.get('/user/reset/verify', function(req, res) {
console.log("Executing verification index.");
res.render("verify/index");
});
app.get('/user/reset/verify/:email/:token', function(req, res) {
console.log("Executing verification change.");
res.render("verify/change");
});
When I go to the verification index page, I see "Executing verification index." printed once on the console. However, when I go to the verification change page, I see "Executing verification change." printed twice on the console.
I have noticed that this is a trend with the routes in my app. Routes that contain parameters are always executed twice, while routes without parameters are only (properly) executed once.
Why are the routes with parameters being executed twice?
The views that are being rendered only contain simple HTML - nothing that would cause another request to the page. Also, I am issuing these requests from a Chrome browser.
Platform/Versions:
NodeJS: 0.5.5 windows build (running on Win 7)
Express: 2.4.6
Connect: 1.7.1
The second request is the /favicon.ico
Try to console log your request.url in your http_server request handler, you'll see the first is the browser url and the next the favicon.
If you are using chrome:
When you write your url chrome send a get request to check the url before you hit enter.
Try to log the middleware url console.log(req.url) position your console aside your broswer then start to write the url, you will see console logging a get access.

Node.js - Why does my callback get called 3 times for each request?

This is my VERY FIRST node app. I'm literally just starting to piece through the API to see what it's all about. I'm immediately confused by the following server code and my console output. Can someone explain why my console.log happens 3 times on a browser refresh?
var http = require('http');
http.createServer(function(request, response){
response.writeHead(200, {'Content-Type': 'application/json'});
response.end("{blah: 1234}");
console.log("Hello!");
}).listen(3000, '127.0.0.1');
Output from a single refresh in the browser is:
Hello!
Hello!
Hello!
What am I missing?
OSX 10.5, Node 0.4.3
Most likely your browser is actually sending these requests.
Change console.log("Hello!") to console.log(request.url) to see what the paths of those requests are.
With Chrome I get only two requests, one for / and one for /favicon.ico.

Resources