How to create a node.js server? - javascript

I'm trying to create my first node.js server and I have some problems.
When I use
var http = require("http");
var server = http.createServer();
server.listen(8888);
No connection can be established to the server.
But when I use this
var http = require("http");
http.createServer(function(request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}).listen(8888);
The server lands ok.
I used this in a file called server.js and runned the command node server.js. I'm using v 0.12.0
What am I missing? Why the server doesn't work on the first case?

The first block of code creates a server and listens on a port.
When you point a browser at it, the browser makes a request and then waits for a response.
You haven't told the server what to respond with, so it sits there doing nothing.
Eventually the browser times out.
In the second set of code, you've told the server how to respond to requests.

Related

Http Server without response.end in Node js

I am having some confusion regarding the response.endin Node js, I have the following code.
const http = require("http");
http.createServer(function(req, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
setInterval(() => {
response.write(new Date() + "\n");
}, 1000)
}).listen(8080);
console.log("Service Running at 8080 127.0.0.1")
Now this above code will start printing the date in the browser after 20 seconds or more, now this code doesn't have any reponse.end, and it's obvious because if there was any response.end() then the code inside the setIntervel would never execute.
But doing this doesn't do anything it takes forever to load the page.
const http = require("http");
http.createServer(function(req, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write("Test");
}).listen(8080);
console.log("Service Running at 8080 127.0.0.1");
But if i add response.end in the above code it will work just fine.
So can anyone explain this weird behavior, that why using setInterval without response.end works.
What you signal as a problem is literally what should happen. The browser asks the server for data, the server starts sending data and never signals an "okay I am done" so that the browser knows the message is done.
The problem here is your idea on how to get data into the browser from the server.
Set up a websocket connection so you can push data from the server to the browser. That's what it's for. Or,
Set up a repeating call in the browser using setTimeout or setInterval or something, and just call the server every second or something, with the server responding with tiny, tiny messages that all actually end.

Electron NodeJS server to server communication using POST

I am working on an assignment for school, and I have decided to make a chat application using Electron and NodeJS. All of the GUI is programmed, except for the server-side of things. My plan was to have two servers, where each would act as its own client AND server, only communicating with each other to send messages.
How would I get each server to communicate using POST requests? Does anybody know any fully functioning npm modules that can be used for this?
you need to use in server A : socket.io
in server B: socket.io-client
Like this:
server A
// Load requirements
var http = require('http'),
io = require('socket.io');
// Create server & socket
var server = http.createServer(function(req, res)
{
// Send HTML headers and message
res.writeHead(404, {'Content-Type': 'text/html'});
res.end('<h1>404</h1>');
});
server.listen(8080);
io = io.listen(server);
// Add a connect listener
io.sockets.on('connection', function(socket)
{
console.log('Client connected.');
// Disconnect listener
socket.on('disconnect', function() {
console.log('Client disconnected.');
});
});
server B
// Connect to server
var io = require('socket.io-client');
var socket = io.connect('http://localhost:8080', {reconnect: true});
// Add a connect listener
socket.on('connect', function(socket) {
console.log('Connected!');
});
This can be done with React js, there's quite examples on github.
Take a look at this examples:
https://github.com/ncuillery/react-chat-project
https://github.com/keithyong/chat-room
It's nice to see someone using Electron, I've just finished my first project with it, and I'm amazed.
As #Arcath has stated, you must use socket.io, it talks between frontend and backend. Whenever someone sends a chat message, React.js handles that message, and emits a socket message which the server recieves. The server then adds the socket message into the database.

No need to set up a local server with Node.js?

I see when I want write a Node.js web application on my local machine, I don't need to set-up a local server using WAMP or MAMP. What is node.js really doing behind the scenes? I am providing this code to make a simple hello world web app:
var http = require("http");
http.createServer(function(request,response){
response.writeHead(200, {"content-type":"text/html"});
response.write("hello world");
response.end();
}).listen(8080);
console.log("server is running....");
When loading in my browser URL bar "localhost:8080" it works.
How this is working as and why don't I need a local server when working with Node.js?
You do have a local server... it's your Node.js application.
When you call http.createServer(), it creates an HTTP server. When you call .listen() on that server, it binds to the requested port, and optionally requested address, and listens for connections. When data comes in on those connections, it responds like any other HTTP server.
The HTTP server uses your request/response callback, firing it whenever a valid HTTP request comes in.
Because node comes out of the box with all the libraries you need to run a webserver, the http library that you are using is opening the 8080 port and handling the request with the function you provided
This part:
function(request,response){
response.writeHead(200, {"content-type":"text/html"});
response.write("hello world");
response.end();
}
No, you don't need it. Because node itself can be your webserver, just like in your example. Node is built on V8, which is chrome JavaScript engine .
Take a look a Express js module that gives you lots of features out of the box

HTML code from node js not interpreted as such by the browser

I have created my first node js application: a simple webserver.
Here's the code:
// Load the http module to create an http server.
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.end("ARD Tagesschau\n");
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
When I connect to the server via my browser I get the full string specified in my code as a web page.
Shouldn't the browser interpret that HTML code and display a link? Why do I get the full HTML code shown as plain text?
You have explicitly said that you are returning plain text, not HTML. The browser therefore treats it as plain text.
If you want HTML to be treated as HTML then say it is HTML:
{"Content-Type": "text/html"}
(Although you should send back an HTML document and not a fragment of HTML).
Following Code works for me:
var http = require('http');
// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/html"});
response.end("ARD Tagesschau\n");
});
// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);
// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");
You need to set the Headers. For more information check in Node API docs here.
Check the difference in your firebug or dev tools to understand how browser interprets differently based on Header Content-Type.

node.js - broadcast message to all the connected

So we have the following node.js code -
var http = require('http');
var server = http.createServer(function (request, response) {
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World! \n");
response.end(");
}).listen(8125);
Let's say I want to broadcast a message to all the connected users,
write method of response in the createServer function doesn't do that.
So how can I broadcast message to all the connected users/clients?
There is a way doing it with pure Node.js? because I'm just learning it now, and I prefer using pure node.js for now..
These are HTTP requests, therefore it isn't possible. HTTP requests start on first connection and end when all the data has been sent.
In your case, the data is
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World! \n");
And then connection is ended
response.end(");
If you're looking for something to keep live connections with, take a look at these:
socket.io - a realtime transport library that supports all platforms, and falls back for older software.
WebSocket-Node - a client and server websocket implementation.
Faye - publish-subscribe messaging system that uses the Bayeux protocol.
I have only used socket.io and this is how broadcasting is done.
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.broadcast.emit('user connected');
});

Categories

Resources