I'm using express framework to run many node applications basically as different node instances. Is it possible to run all the applications as single node instance (like routing with different url and same port) ?
Sure:
var express = require('express');
var main = express();
var app1 = express();
var app2 = express();
main.use(app1);
main.use(app2);
app1.get('/app1/test', function(req, res) {
res.send('handled by app1');
});
app2.get('/app2/test', function(req, res) {
res.send('handled by app2');
});
main.listen(3012);
If each app has their own unique URL prefix, you can also use this:
var express = require('express');
var main = express();
var app1 = express();
var app2 = express();
main.use('/app1', app1);
main.use('/app2', app2);
app1.get('/test', function(req, res) { // GET /app1/test
res.send('handled by app1');
});
app2.get('/test', function(req, res) { // GET /app2/test
res.send('handled by app2');
});
main.listen(3012);
Related
I have a small project with NodeJS Express server and Angular2 frontend. The server has an API interfaces. The main part of this is: /api/alert. I want to do the following: If the /api/alert get an request then socket.io broadcast an event to all connected clients.
My server structure is the following:
server.js
var http = require('http'),
express = require('express'),
app = module.exports.app = express(),
port = process.env.PORT || 3000,
mongoose = require('mongoose'),
bodyParser = require('body-parser'),
db = require('./config/db'),
path = require('path');
mongoose.Promise = global.Promise;
mongoose.connect(db.url);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'dist')));
var routes = require('./server/routes/index');
routes(app);
var server = http.createServer(app);
var io = require('socket.io')(server);
server.listen(port);
console.log('Server started on: ' + port);
server/routes/index.js
const deviceRoute = require('./devicesRoute');
const alertRoute = require('./alertsRoute');
module.exports = function(app) {
deviceRoute(app);
alertRoute(app);
}
server/routes/alertRoute.js
'use strict';
module.exports = function(app) {
var alertsService = require('../services/alertsService');
app.route('/api/alert')
.post(alertsService.createAlert);
};
server/service/alertService.js
'use strict';
exports.createAlert = function(req, res) {
// do something in database
// I want to broadcast to all client HERE
};
I can't pass the io and server variables to the function (from server.js). How can I do that? What is the easiest way?
Thank you!
First you would want to export both the app and server objects from server.js and pass your socket to your response in middleware as follows:
var app = express();
var server = http.createServer(app);
var io = require('socket.io')(server);
app.use(function(req, res, next){
res.io = io;
next();
});
...
module.exports = {app: app, server: server};
You can then require the server instance you created in server.js (depending on where you are requiring it from) as
var server = require('../server').server;
Since you added socket.io to the response object, you can use it in your services as
'use strict';
exports.createAlert = function(req, res) {
// do something in database
// I want to broadcast to all client HERE
res.io.emit("broadcast", "clients");
};
For example :
server.js file
var express = require('express'),
app = express(),
port = 3000,
routes = require('./app/routes/apiRoutes');
routes(app);
app.listen(port);
routes.js file
'use strict';
module.exports = function( app ) {
var api= require('../controllers/apiController');
app.route('/get').get(api.get);
};
apiController.js file
'use strict';
exports.get = function(req, res) {
// console.log( req.app ); // access it but it didn't work ?
// here want to access app to set cookie and changed cookie ?
};
if there is another way please help me thanks :)
If I correct understand your question, with routes you can do something like this:
In routes.js file:
var router = require('express').Router()
router.get('/home', function(req, res, next) {
res.render('index')
})
module.exports = router
In server.js file:
var mainRoutes = require('./routes.js')
app.use(mainRoutes)
Best way (in my opinion) to use controllers from another file it's use exports.functionName notation:
In someController.js file:
exports.homePage = function(req, res) {
res.render('index')
}
So, your router will looks like this:
var router = require('express').Router()
var someController = require('./someController.js')
router.get('/home', someController.homePage)
module.exports = router
Do different way, use route in app.use
app.js:
const
express = require('express'),
app = express(),
port = 3000,
routes = require('./app/routes/apiRoutes');
app.use(routes);
app.listen(port);
apiRoutes.js:
const
router = require('express').Router(),
apiController = require('../controllers/apiController');
router.get(
'/get',
apiController.get);
module.exports = router;
Check this example: app.js , some route file
I write my app.js including all the routes in the main file and everything was working well. After my goal was to make the project more clear by moving the routes in a different files but it is not working.
I'm passing an object instead of a middleware function and I don't know how to fix it in the right way.
So this is my app.js file:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var morgan = require('morgan');
var mongoose = require('mongoose');
var myRoutes = require('./app/routes/myRoutes.js');
...
//parser for getting info from POST and/or URL parameters
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//for log requests to console
app.use(morgan('dev'));
app.use('/myRoutes', myRoutes);
app.get('/',function(req,res){
res.end('Welcome Page!');
});
//Server Start
app.listen(port);
console.log('server start at port ' + port);
And the app/routes/myRoutes.js contains the following code:
var express = require('express');
...
var myRoutes = express.Router();
myRoutes.get('/users',function(req,res){
...
});
myRoutes.post('/setup',function(req,res){
...
});
myRoutes.post('/remove', function(req,res){
...
});
module.export = myRoutes;
I also tried this:
var express = require('express');
var myRoutes = express.Router();
myRoutes.route('/')
.get(function(req, res, next){
res.end('myRoute Get');
})
.post(function(req, res, next){
res.end('myRoute Post');
});
module.export = myRoutes;
But again it seems not passing a middleware function.
My second option code
var express = require('express');
var myRoutes = express.Router();
myRoutes.route('/')
.get(function(req, res, next){
res.end('myRoute Get');
})
.post(function(req, res, next){
res.end('myRoute Post');
});
module.export = myRoutes;
is working fine! I just write it in a wrong way
module.export = myRoutes;
isntead of
module.exports = myRoutes;
Hi this is more of additional tips on the question. You main js file would definately need to load a lot of routes and i found importing all of them is a lot of work. Rather use require-dir module to load all the routes like
const loader = require('require-dir');
var app = express();
var routes = loader('./routes');
for (route in routes){
app.use("/"+route,routes[route]);
}
needless to say define all routes inside routes folder and export Router module in each one of them like
var router = express.Router();
router.get(....);
module.exports = router;
I want to create a site with this structure:
--mysite.com
--mainserver.js
-----mysite.com/project1
-----server.js
-----mysite.com/project2
-----server.js
In each project folder I want to run a separate node application. Im trying to do this using vhost module.
In my mainserver.js I have this to test:
var express = require("express");
var app = express();
var router = express.Router();
var vhost = require('vhost');
var app2 = express();
app2.get('/', function(req, res) {
res.send("echo");
});
app.use(vhost('localhost/project1', app2));
app.get('/', function(req, res) {
res.send("hi");
});
var port = Number(process.env.PORT || 5000);
app.listen(port, function() {
//console.log("Listening on " + port);
});
When navigating to localhost:8000 I see the "hi". But when I navigate to localhost:8000/project1 I get Cannot GET /test...
Please help!
I believe this is what you are trying to achieve. (Without use of vhost)
project1/index.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res) {
return res.send('project 1');
});
// Other routes specific to project 1 here
module.exports = router;
Project2 could be set up similarly.
server.js
var express = require('express');
var app = express();
app.use('/project1', require('./project1'));
app.use('/project2', require('./project2'));
var port = Number(process.env.PORT || 5000);
app.listen(port);
Why doesn't the following work ?
app.js
reports/
├── index.js
└── batch.js
in app.js :
app.use('/reports', require('./reports')
in index.js :
var express = require('express');
var batch = require('./batch');
var app = express.createServer();
...
app.use('/batch', batch);
module.exports = app;
in batch.js :
var express = require('express');
module.exports = function() {
var app = express.createServer();
console.log('I am here');
app.get('/', function(req, res) {
console.log('I am there');
});
return app;
};
calling GET /reports/batch prints I am here but doesn't print I am there
Can anyone pinpoint me to the problem ?
Thanks
try this:
in app.js :
var express = require('express'),
http = require('http'),
path = require('path');
var app = express.createServer();
require('./reports')(app);
in reports/index.js :
module.exports = function(app){
var batch = require('./batch')(app);
app.use('/batch', batch);
}
in batch.js :
module.exports = function(app) {
console.log('I am here');
app.get('/', function(req, res) {
console.log('I am there');
});
};
Note that you may need to modify the app.get routing as needed. but basically the idea here is instead of calling createServer all the time just keep passing it down the chain from one module to the next.
Hope this helps!
Here is my app.js. It passes db and app to the feature.js. Basically they share the same app variable.
in app.js
var express = require('express'),
http = require('http'),
path = require('path'),
mongoose = require('mongoose'),
db = mongoose.connect('mongodb://abc:123#xxxx.mongohq.com:90000/app123423523');
var app = express();
//here you set app properties
require('./routes/feature').with(app, db);
in feature.js
module.exports.with = function(app, db) {
//do work
}
It seems that I have forgotten javascript a little.
I was doing
app.use('/batch', batch);
batch is equal to
function() {
var app = express.createServer();
console.log('I am here');
app.get('/', function(req, res) {
console.log('I am there');
});
return app;
};
Instead I should have done
app.use('/batch', batch());
Which equals to what express.createServer() returns which is what app.use expects to get