How to create a simple http server with NodeJS? - node.js

I am new in NodeJS, I want to create a simple http server, Just send a 'Hello World' back to the client. I did something. If anyone, can check out my code if I did it right, if not add yours, I will be really appreciated.
Here is my code.
var http = require("http");
var server = http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.write("<html>");
response.write("<head>");
response.write("<title>Hello World!");
response.write("</head>");
response.write("<body>");
response.write("Hello World!");
response.write("</body>");
response.write("</html>");
response.end();
});
server.listen(80);
console.log("The Server is listening now...");

Your node.js is fine, however, you are missing a closing title tag in your html, eating up the rest of your page. Modify your title line so it is like so:
response.write("<title>Hello World!</title>");
and you should see output on the browser.
Happy Programming! :)

Related

Node' \n' error when creating localhost server

I'm following along in a MongoDB course and came to a basic Node Hello world server tutorial:
Basically it just displays Hello World on localhost:8000
So I typed out the code below and when I tried to run it, ran into the following error:
var http = require('http');
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("Hello, World"\n);
});
server.listen(8000);
console.log("Server running at http://localhost:8000");
If I remove the \n it will work fine, just curious as to how does the teacher get his to work with it and no errors?
It's just a typo. It should be: response.end("Hello, World\n");.

Node.js double console.log output

I'm learning Node.js and I'd like to understand the "why" when code spits out duplicated console.log outputs but only a single response.write outputs.
Heres my simple code example:
var http = require('http');
http.createServer(function(request, response){
response.writeHead(200, {'Content-type': 'text/plain'});
console.log('hello 1');
response.write('Hello world');
console.log('hello 2');
response.end();
}).listen(8000);
And on my console/terminal I get:
hello 1
hello 2
hello 1
hello 2
Thanks.
Some browsers also send a request to locate the favicon.ico file. Since the file isn't present by default, a browser(Chrome in particular) will always send two requests: one for the originally requested file and another for favicon.ico. This is a known bug in Chrome and has been fixed in version 29. Firefox, however, requests for favicon.ico only for the first request. If you console.log the request URI path, you must see a request to localhost:8000/favicon.ico.
var http = require('http');
http.createServer(function(request, response){
response.writeHead(200, {'Content-type': 'text/plain'});
if(request.url === '/favicon.ico') {
console.log('Favicon was requested');
}
console.log('hello 1');
response.write('Hello world');
console.log('hello 2');
response.end();
}).listen(8000);
I've had the same problem myself, and I found out that using something like
var http = require('http');
http.createServer(function(req,res) {
if(req.url === '/favicon.ico')
{
//everything here is ignored
}
res.writeHead(200,{"Content-Type": "text/plain"});
res.write("Hello World\n");
res.end();
console.log("Connection made");
}).listen(1337, "127.0.0.1");
console.log("Server running at http://127.0.0.1:1337/");
is enough to avoid that behaviour. For some reason, when I check req.url and compare it to '/favicon.ico' nothing is sent to console, in fact, everything in that block is ignored. I don't know if this behaviour is expected, but you sure could try it.
If you output the header you're telling the server that you found favicon, hence the response is processed and no matter what you get that double console.log(). Instead, end it before sending a writeHead() or send a 404.
var http = require('http');
http.createServer(function (req, res) {
if(req.url === '/favicon.ico') {
res.writeHead(404);
res.end();
} else {
res.writeHead(200, {'Content-Type': 'text/plain'});
}
//code here...
res.end();
}
i think that this problem still persists in chrome Version 67.0.3396.87 (32-bit) because when i ran my nodeJS script i saw 2 console.log() statements one was able to print out the query the other was not, so i corrected my code so as to see console.log() statements only once, it was simple all i had to do was add a return statement if the request.url was == (equal to)"/favicon.ico" in the beginning of the code and everything worked fine
previous code
var http = require('http');
var url = require('url');
http.createServer((request,response)=>{
var q = url.parse(request.url,true).query;
console.log(request.url);
console.log('hey there! we got a request from '+q.name+' !');
}).listen(8080);
and the output was :
/?name=harshit
hey there we got a request from harshit !
/favicon.ico
hey there we got a request from undefined !
code after debugging :
var http = require('http');
var url = require('url');
http.createServer((request,response)=>{
if(request.url == "/favicon.ico"){
return ;
}
var q = url.parse(request.url,true).query;
console.log(request.url);
console.log('hey there! we got a request from '+q.name+' !');
}).listen(8080);
output :
/?name=harshit
hey there we got a request from : harshit !
in a nutshell the duplication as it is mentioned before is a result of the favicon request so to avoid this problem, I propose you this simple snipet:
var pathname = url.parse(request.url).pathname;
if(pathname != '/favicon.ico')
console.log('hello 1');
It can also be a Chrome plugin like JSONView. I was just trying to figure it out until I tried incognito and realized it was no longer causing the problem. Also was requesting a JSON file.

node.js 8080 port isn't listening

I'm following the node.js tutorial in here,
http://net.tutsplus.com/tutorials/javascript-ajax/learning-serverside-javascript-with-node-js/
this is the code,
var sys = require("sys"),
http = require("http");
http.createServer(function(request, response) {
response.sendHeader(200, {"Content-Type": "text/html"});
response.write("Hello World!");
response.close();
}).listen(8080);
sys.puts("Server running at http://localhost:8080/");
in here, it says run like this url,
server's ip:8080/
but if i do this,
it just shows, cannot connect to this url.
i opened 8080 port in the server.
===========================
I'm assuming something is screwed up with codeigniter url helper...
The tutorial may be using an incorrect or deprecated method. Replace
response.sendHeader(200, {"Content-Type": "text/html"});
with
response.writeHead(200, {"Content-Type": "text/html"});
and
response.close();
with
response.end();
I Agree with the answer of Third .... make those changes and if it is local use this URL
http://127.0.0.1:8080/
But
If you are running your server not on localmachine but on something like webserver(AWS), You have to let the security of AWS firewall to allow the port to be public on the internet and also remember to use the AWS instance URL
http://AWSinstanceURL:portno/
Use this one
//Lets require/import the HTTP module
var http = require('http');
//Lets define a port we want to listen to
const PORT=8080;
//We need a function which handles requests and send response
function handleRequest(request, response){
response.end('It Works!! Path Hit: ' + request.url);
}
//Create a server
var server = http.createServer(handleRequest);
//Lets start our server
server.listen(PORT, function(){
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://localhost:%s", PORT);
});
Now open http://localhost:8080 and u will get your result.

Access nodejs app on koding.com

I'm trying to upload two node.js files to koding.com and run them.
index.js contains:
var server = require("./server");
server.start();
And server.js
var http = require("http");
var url = require("url");
function start() {
function onRequest(request, response) {
console.log("Request received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(6665, '0.0.0.0');
console.log("Server has started.");
}
exports.start = start;
I typed in vm terminal jstq#vm-0:~$ node Web/IkapNodeJS/index.js
it gives me Server has started.
If im going to http://jstq.kd.io/IkapNodeJS/index.js - i see index.js contains.
When im adding :6665 to that url - url not found.
How do i see page with hello world?
If you're running your application on 6665, the you would access it with http://jstq.kd.io:6665/. You should see your Hello world there.
Node does not run like a cgi script; you don't point to the file to run it, you run it with a process (node). When the server is running on a specific port, the content will be available on any address/hostname that points to that machine so long as you specify the proper port.
HTH,
Aaron

Socket.io-client on node.js works only once

I want to create new sockei.io-client on the server side (with node.js) every time when server gets request. But the code below works only once and then sockei.io-client does't response. Application doesn't stop, no errors.
var http = require("http");
http.createServer(function(request, response) {
var io = require('socket.io-client');
localSocket = io.connect('http://localhost:9876/');
localSocket.on('connect', function (data) {
response.writeHead(200, {"Content-type": "text/plain"});
response.write(data.name);
response.end();
localSocket.disconnect();
});
}).listen(8080);
Socket.io server (on localhost:9876) works well - it serves clients with names (which is
data.name
in the code here).
What is wrong?
UPDATE: The problem is solved by myself: To run multiple connection for socket.io-client need to add connect option {'force new connection': true}, like that:
localSocket = io.connect('http://localhost:9876/', {'force new connection': true});
Thank you!
For those who found this on google - there is a solution for this right now:
Socket.disconnect() kicks the client (server-side). No chance for the client to stay connected :)
force client disconnect from server with socket.io and nodejs
I think you just have to remove the disconnect() line.

Resources