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
Related
Hie,
I am developing a Nodejs (Express) web app and pretty much new to this technology. So far I see that there can only be one point of entry mine being my the server.js file. Now it seems all requests and/or processes should be initiated here which is fine for a smaller application, but my site has about 25 page routes already all of who's request should be handle here. I also have a dozen or so Ajax requests are handled here. Now even though I am processing different functions e.g CRUD operations in separate files, I still fear at some point my code will become unreadable as the server.js file get longer
const express = require("express")
const path = require("path")
const exphbs = require("express-handlebars")
let app = express()
app.set("views",path.join(__dirname,'templates'))
app.engine('handlebars',exphbs({defaultLayout:'main'}))
app.set('view engine','handlebars')
app.set('port',(process.env.PORT || 3000));
app.get('/',(req,res)=>{
res.render('home',{'title':'Home'});
});
app.get('/home',(req,res)=>{
res.render('home',{'title':'Home'});
});
app.get('/register',(req,res)=>{
res.render('register',{'title':'Register'});
});
app.use(express.static(path.join(__dirname, '/public')));
app.listen(app.get('port'),()=>{
console.log(`Server started on port : ${app.get('port')}`)
})
So far my server.js is this small, but it just hit me that I have 25 pages and multiple Ajax processes on each.
Yes, you have to structure your routes. For that, you have to look at Express Router. You have to create different route files based on a specific resource.
/routes/homeRoutes.js
const express = require("express");
const router = express.Router();
router.get('/',(req,res)=>{
res.render('home',{'title':'Home'});
});
module.exports = router;
server.js
const homeRoutes = require("./routes/homeRoutes");
app.use("/api/v1/home", homeRoutes);
Also, have a look at the following links for a better understanding of project structure and express router.
https://expressjs.com/en/guide/routing.html
project structure
I think what you are looking for is splitting the code up in local modules. You can place parts of your code in separate files, include module.exports at the end and then require(./filename.js) them in your server.js.
You can see an example here: https://www.tutorialsteacher.com/nodejs/nodejs-local-modules
I am following an on-line tutorial of implementing in MEAN. Everything looks great. Except when it comes to routes. I understand that routes need to be in a javascript files (js extension). It's okay with a small web site. But as the number of requests grow, I would like to put them in separate files. I looked up in SOF for how to include files in Javascript. It is non-trivial. Has anyone faced this issue before? Can anyone comment?
Thanks
You can use Router Middleware by using express.Router(). This allows you to break your routes into different files. On a side note, middleware is very powerful and is worth learning about, its a huge part of Express.
Say you have an app that has a /users section. You can create a separate routes file called users.js that contains all routes that pertain to your /users resources. Then inside your server.js where your main Express app is listening, you can assign the users.js routes to the /users resource using app.use().
You can have as many routers as you'd like, all routes are read top-down when Express is deciding which route to use.
./routes/users.js
// Create an express router
var router = require('express').Router();
// Define a route for GET /
router.get('/', function(req, res) {
res.status(200).send('Welcome to /users');
});
// make our router available for require() statements
module.exports = router;
server.js
var express = require('express');
var app = express();
// Users routes
var users = require('./routes/users');
// Tell our app to use the Users routes defined in ./routes/users.js
app.use('/users', users);
app.listen(process.env.PORT || 3000, function() {
console.log('listening');
});
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);
I have a situation where I have tow express js apps App1 and App2 running on port 80 and 8080 respectively. I have declared these apps in same js file.....now I wanted to share some data from App2 request to App1. Is it possible if yes how I can do that? or can we forward App2 request to App1 directly.
You can easily do this with vhost() in Express. All you have to do is
var express = require('express');
var app = express();
app
.use(express.vhost('localhost', require('/path/to/website1/app.js').app))
.use(express.vhost('localhost2', require('/path/to/website2/app.js').app))
.listen(3000);
This will listen on port 3000, and check for specific host names - in this case, localhost and localhost2. If one of those hosts match, it will get an instance of their 'app' to run/use.
In this case you will have to export your app object from app.js to use all the methods and API's you have, You can simply do this by
var express = require('express');
var app = exports.app = express();
I just set up a NodeJS server and wanted to use the vhost function from Express to allow for easy project setup. I want to be able to create a new directory for a new project without going through the hassle of creating new subdomains etc.
Basically, I want to be able to reach project1 at node.domain.com/project1 and project2 at node.domain.com/project2.
I'm now running server.js, which is located in the root (node.domain.com/server.js) and contains:
var express = require('express');
var app = express();
app
.use(express.vhost('node.domain.com', require('./project1/app.js').app))
.use(express.vhost('node.domain.com', require('./project2/app.js').app))
.listen(3000);
It's all working fine, when I go to node.domain.com/project1 I get the results of ./project1/app.js but whenever I change something in any of the app.js files it requires a restart (Ctrl+C followed by node server.js) for it to update the changes.
And the contents of app.js are, for example:
var express = require('express');
var app = exports.app = express();
app.get('/project1', function(req, res){
res.send('Hello World [/project1]');
});
Any idea why this is?
A thing to note is that I also run Apache on the same server, and I'm using this guide to allow both servers to run on port 80 (but accesible via different subdomains).
Oh! I feel dumb now, seems like I need to use something like forever, with its w flag.