I was referring to some online tutorials for establishing a Node server using Express 4. I will make my question very simple and easy to understand.
The main app.js file has the following lines (other code lines like middlewares etc. are not show here)
var express = require('express');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
app.use('/', routes);
app.use('/users', users);
I have tested the above code. Included the index.js and users.js inside the routes folder. This worked perfect. This means that the http server is already created.
But, my confusion raised, when I say another type of coding done in another site. It has the following lines of code.
var express = require('express'),
routes = require('./routes'),
http =require('http’);
var app = express();
My first confusion is, why do we need to use the http middleware.
The code further creates a server like this
var server = http.createServer(app);
Since, I am using the Express framework, why do we need to create the server, this way
Reference can be found here https://github.com/azat-co/practicalnode/blob/master/ch5/blog-express/app.js#L72
Any help would be highly appreciated. Thanks in advance.
Perhaps the developer wanted to create a raw http server for some other specific use later on? Strictly speaking, it is not necessary to do that.
The following is perfectly sufficient to create an http server and begin listening for connections using express:
var express = require('express');
app = express();
app.listen(3000);
in express best way is:
app = express();
app.listen(3000);
in theory this:
var server = http.createServer(app);
could be used to reuse http server, for example to run sockets.
But app.listen also return http server like http.createServer(app);
We can do:
var server = http.createServer(app);
var io = require('socket.io')(server);
But we also can:
var server = app.listen(3033);
var io = require('socket.io')(server);
When createServer(app) may be useful? if we want listen to http i https:
http.createServer(app).listen(80);
https.createServer(options, app).listen(443);
Related
I have this Problem when I start my Backend, I want to test the post request in Postmann but I have this error, how can I fix it?
this is my Server . j s
const app = express() Should come before your middlewares... app.use(...)
Also make sure to connect your mongo database before your app initialization not after app.listen(...). Your application should depend on your database, throw error if database didn't connect, all this should happen in try{}catch(){}
The app variable is used before you declare it. Move your const app = express(); upward. Like this:
const express = require('express');
const app = express();
You are calling app.use methods before initializing app.
Just move const app = express() before app.use.
Learning Nodejs for my personal projects. Analysing other developers code examples, watching youtube videos. I noticed one thing that I don't understand completely, why most of nodejs examples I come across have a code part for http server initiation and port listening? But application itself not using any http related things like processing http requests/responses. For example:
const express = require('express')
const path = require('path')
const http = require('http')
const cors = require('cors')
const PORT = process.env.PORT || 5000
const app = express();
const server = http.createServer(app).listen(PORT, () => console.log(`Listening on ${PORT}\n`))
app.use(express.static(path.join(__dirname, 'public')))
app.use(cors({ credentials: true, origin: '*' }))
If my nodejs application is a script that needs to be run on server side that collects some information from other API's and stores in a database, etc., do I need to create and start HTTP server anyway?
why most of nodejs examples I come across have a code part for http server initiation and port listening?
Because that's how people use nodejs most of the time: as a web server. Which doesn't mean it is mandatory or even a good practice.
do I need to create and start HTTP server anyway?
Of course not. Why would you do that if you don't need it? Do not worry about tutorials or examples, these don't know about your case and your needs.
I have two web application node.js servers and I need to have them under one web address.
It should work like this:
example.com/wa/* -> redirect to example.com:pppp
others example.com/* -> redirect to example.com:qqqq
I have experimented with http proxy module, but it doesn't work, maybe the problematic part is the fact, both servers are https not http.
Using Express you can do something like this
var express = require('express');
var http = require('http');
var app = express();
app.use('/wa/*', function(req, res){
req.redirect('example.com:pppp')
});
app.use('/*', function(req, res){
req.redirect('example.com:qqqq')
});
http.createServer(app);
Not tested, but it should work.
Note: The /wa/* route must come before the /* route. otherwise all requests will get redirected by the first middleware
Hello guys i'm new to node js and started researching and working on some tutorials. I just want a better understanding or clarification on a doubt i had. So i came across the in built module http. This helps in creating a a basic web server. Now express module is a web framework that is built on top the http module that makes it easy using a fully wedged web server without reinventing the wheel. Now I came across this code:
var express = require( 'express' )
, http = require("http")
http.createServer( options, function(req,res)
{
app.handle( req, res );
} ).listen(8080);
But in express one could simply just do this
var express = require('express');
var app = express();
app.listen(8080, function() {
console.log('Listening on ' + 8080);});
What's the difference between both? Don't they both accomplish the same thing. If not what's the difference and advantage of using the first approach. Should one adhere to the first approach as it's a good programming practice. That's my doubt as i just want a clear understanding if there's any difference.
Why combine http module with express module
There's really no reason to create your own http server using the http module. Express will just do that for you with app.listen() just fine and save you little bit of typing.
If you were creating an https server, then you would need to use the https module and pass security credentials to https.createServer(...) in order to create a properly configured server. Express does not have the ability to create a properly configured https server for you automatically.
If you look at the Express code in GitHub for app.listen(), it shows this:
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
So, there's really no difference (other than a little less typing) when you use app.listen() or create your own http server and then use app as the listener to that server.
So, these two code snippets are identical in function:
var app = require('express')();
app.listen(8080);
app.get('/', function(req, res) {
res.send("hello");
});
The above code is functionally identical to:
var http = require('http');
var app = require('express')();
http.createServer(app).listen(8080);
app.get('/', function(req, res) {
res.send("hello");
});
Of course, if you're trying to set up https servers or add custom options to the .createServer() method, then you will set up your own server first and then pass app to it as the listener. app.listen(...) is just a shortcut when the default http.createServer() works fine.
I have two Express JS application and I want to add a route for one inside the other so when this link is requested it goes to the sub-application. Is that possible??
Example:
The main application is accessed through the link www.linktoapp.com and it is written in Express js.
Now I have developed another Express js application and I want to access it through the link www.linktoapp.com/secondapp
My question is can I add this route (/sceondapp) in the main application so I can access it like I said?
Thanks.
You could always have two separate express processes running on 2 ports and then reverse proxy the requests.
https://github.com/nodejitsu/node-http-proxy
Your question is a bit confusing! What I understand from your question:
You have two expressjs application running. Two application can't run on same port. Two application can however run on two different ports. See example below.
var express = require("express");
var app1 = express(); //created the first app
var app2 = express(); //created the second app
app1.get("/",function(req,res){
res.send("<html><body><a href='/sec'>go second app</a></body></html>");
// created a link to app2
});
app1.get("/sec",function(req,res){ // redirection to second app
res.redirect("http://localhost:3001/");
})
app2.get("/",function(req,res){
res.send("welcome to second app");
});
app2.listen(3001,function(){ // app2 is listening on port 3001
console.log("app two is listening on 30001 ")
});
app1.listen(3000,function(){ // app2 is listening on 3000
console.log("app1 is listening on 3000");
});
What you want is to create an Express sub-app. Express sub-apps share routes, views, sessions, etc with the main app.
For example, let's say you want one node app, s_app.js, to be a sub-app of another, p_app.js.
s_app.js
var express = require('express');
var app = module.express = express();
// set routes for userjs
app.get('/path_1', function(req, res){
// display path_1
});
p_app.js
var express = require('express');
var app = express();
var s_app = require('s_app'); // mount s_app.js
app.use(s_app);
// now p_app and s_app share routes, views, sessions, etc
If you want more detail, take a look at a tutorial I wrote on how to build node.js sub-apps