express and http server usage togather - node.js

Gone through code as below couldnt understand the working of code 1...what is the difference between the two codes below
**
What is the point of using http and express togather in code 1?
Code1
var app = require('express')();
var http = require('http').Server(app);
app.get('/', function(req, res)
{
res.sendFile(__dirname+'/index.html');
});
http.listen(3000, function()
{
console.log('listening on *:3000');
});
The same thing can be done as
Code2
var express=require('express');
var app=express();
var socket=require('socket.io');
app.get('/',function(req,res){
res.sendFile(__dirname+'/index.html');
}).listen(8080);
console.log("Listening to port 8080");

You're asking about the difference of expressjs own server and http server. They are different in many ways.
Solved here

The app object conventionally denotes the Express application which is created by top level express() function exported by the Express module.
http.listen(): Starts the HTTP server listening for connection
In the second case it works app.listen() which binds and listens for connection on the specified port and it identical to http.listen()

Related

Why do I need to add "require("http")" when I already have express?

I am trying to follow this tutorial on creating a simple chat application using socket.io. I am at the part of the tutorial where I have to insert all of the code below into a js file and initiate it. I just don't understand why the 2nd of code exist, I heard that express can do a lot more than http. Instead of using the "http.listen" code, can't "app.listen" be used and "app" passed to "io" instead?
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Why do I need to add “require(”http“)” when I already have express?
You don't have to manually load the http module yourself. You use express to create an http server for you (it will load the http module for you) and integrate it with socket.io without manually loading the htttp module like this:
const app = require('express')();
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
const server = app.listen(3000, function(){
console.log('listening on *:3000');
});
const io = require('socket.io')(server);
io.on('connection', function(socket){
console.log('a user connected');
});
Internally, app.listen() loads the http module for you, creates a server and then starts it, returning the server object which you can then use with socket.io.
Inside of express, this is the code for app.listen():
const http = require('http');
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
So, somebody had to load the http module. If you use app.listen(), the express will do it for you.
You are right. Express is a framework that sits on top of the nodejs application and provides a much easier,provided more middleware to handle routes, session and cookies and more efficient way to create server as such
var express = require('express');
var app = express();
app.listen(3000);
In this example, for the purpose of creating a socket between different channels, you have to use HTTP to indicate that the socket is used to handle HTTP requests/responses. You simply can't pass an entire express application to io.

Node.js server with http get json

I want to create a simple Node.js server to do the following :
With my application I just do the command http.get(Node.Js_Server_address/json) to get the json file data stored on my server.
Could please help me with a tutorial? Any help would be appreciated!
This is very simple example of node.js server:
var app = require('./app');
var http = require('http');
var server = http.createServer(app);
server.listen(8080, function() {
console.log("listening to: http://127.0.0.1:8080");
});
// routing
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
there is a nice tutorial here and here ...
you can use npm to install node.js and all the packages that you need for it.
hope it helps.
There are lots of examples on this topic, i think you should make some googling before next time.
You can create a REST server via express module of nodeJs. In your server folder use npm install express to download express module. You can get more information about express from here. After that create a server.js file in your server folder.In server.js
var express = require('express');
var app = express();
var PORT = 8080;
/* req stands for request, res stands for response */
app.get('/json',function(req,res){
res.json(yourData);
})
app.listen(PORT,function(){
console.log('Express is listening port:' + PORT + '!');
})
So this should do the work. Let me know if this helps you.

Creating web server with express (node.js)

js and am trying to create a web server and server side code for my web application.
I understand express is used to get access to all static files.
I am trying to start a simple server using express as follows:
var express = require("express");
var url = require("url");
var http = require("http");
var port = 3000;
var app = express();
app.use(express.static(__dirname + "/Client"));
http.createServer(app).listen(port, function(req,res){
console.log("Server running at: " + "http://" + port);
res.writeHead(200,{
"Content-Type":"text/plain"
});
});
I cant seem to do anything with my res variable in my callback, which I am trying to use as a response object. Allowing me to do things like:
res.end(¨hello world¨);
Is this callback even allowed, or how can I start sending responses etc. I am on virtual box (linux) machine, and using res always gives error (undefined methods etc.). Thanks in advance,
http.createServer(app).listen(port, [hostname], [backlog], [callback])
There are no parameters given to the callback function. This is why req and res are undefined.
So you may change your code to:
app.listen(port, function(){
console.log("Server running at: " + "http://localhost:" + port);
});
app.get('/', function(req,res) {
res.status(200).send('Hello World!')
})
So take a look at the documentation of app.listen() and app.get()

Express.js showing ERR_CONNECTION_REFUSED

I have installed node(v4.1.2) and express(4.13.3)
Node Server code:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
After running the node file and upon calling http://localhost:3000/ gives me ERR_CONNECTION_REFUSED.
Have you run in powershell at server directory?
node app.js
You are listening on port 3000.
So Try http://localhost:3000
At first install Node.js body parsing middleware.
Installation: npm install body-parser
Then add the following lines:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
I think your problem will be solved. For more details, visit -
http://expressjs.com/en/resources/middleware/body-parser.html

How to use sticky-session with cluster in express - node js

I created a cluster depending app with reference to this question
But I started facing issues in session handling. how to use sticky-session in express js with cluster.
I was trying to use this npm module. But this resulted in the same situation. how to fix this session issue.
sticky(http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
}););
Finally found solution just try this code. Its maintain sticky as well as it uses all the cpus [ process ] for other clients. You can use express cluster sticky session using following code. You can get sticky-session here https://github.com/indutny/sticky-session
var http = require('http');
var cluster = require('cluster'); // Only required if you want the worker id
var sticky = require('sticky-session');
var express = require('express');
var app = express();
app.get('/', function (req, res) {
console.log('worker: ' + cluster.worker.id);
res.send('Hello World!');
});
var server = http.createServer(app);
sticky.listen(server,3000);
It has nothing to do with Express.
You just forgot the listen() on the sticky function.
sticky(
http.createServer(app).listen(app.get('port'), function () {
console.log('Express server listening on port ' + app.get('port'));
});
).listen(app.get('port'),function() {
console.log('Sticky server started on port' + app.get('port'));
});

Resources