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
Related
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 get undefined when I use the app.locals. I am just using app.local as config variable. how do I use it inside the listen(PORT)
app.js
app.locals = {
socket_io_host: 'http://localhost:3001',
socket_io_port: "3001",
};
routes/index.js
var express = require('express');
var router = express.Router();
var server = require('http').Server(express).listen(app.locals.socket_io_port);
var io = require('socket.io')(server);
console.log("["+app.locals.socket_io_port+"]");
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express',point1: point1,point2: point2 });
});
You have to require it:
app.js:
module.exports = {
socket_io_host: 'http://localhost:3001',
socket_io_port: "3001",
}
index.js:
// put as the first line
var app = require('./app');
basically im just trying to seprate routes, models, and controller in node.js application.
i have following files to setup very very basic node.js application.
controller/cv.js
module.exports = {
get: function(req, res, next){
console.log("GET REQUESTS")
next();
}
}
routes/cv.js
var express = require('express');
var CvRouter = express.Router();
var CvController = require('../controller/cv')
CvRouter.get('/', function(req, res, next){
console.log("GET REQUESTS")
next();
})
module.export = CvRouter
app.js
const express = require('express');
const bodyParser= require('body-parser')
var path = require('path')
const app = express();
app.use(bodyParser.urlencoded({extended: true}))
app.use(bodyParser.json())
var router = express.Router();
require('./router')(app)
app.listen(3000, function() {
console.log('listening on 3000')
})
router.js
var CvRouter = require('./routes/cv')
module.exports = function(app) {
app.use([CvRouter]);
};
Basicaly this last file router.js is generting error when i use app.use([CvRouter])
ERROR is: throw new TypeError('app.use() requires middleware functions');
how i can resolve it? i also know its returning object of router. and app.use expecting function in parameter. but how i can achieve my desired MVC pattern of node.js?
as said in comment - you have a typo.
The file routes/cv.js contains module.export instead of module.exports, that makes CvRouter undefined.
Kill the array literal
var CvRouter = require('./routes/cv')
module.exports = function(app) {
app.use(CvRouter);
};
An endpoint works fine if added directly to my server.js file:
app.post('/test', function(req,res) {
res.status(200).send({"message" : "OK"});
});
but in an attempt to refactor the app I include a file called api.js from server.js like this:
var routesApi = require('./server/routes/api');
app.use('/v1', routesApi);
and it looks like this:
var express = require('express');
var router = express.Router();
module.exports = function() {
router.post('/test', function(req, res){
res.status(200).send({"message" : "OK"});
});
return router;
}
but if I try and hit this end point the req "stalls" as there is no response. What am I doing wrong?
Because of the way you exported your router, you need to invoke routesApi when adding it to the middleware stack via .use(). This is how that might look like
app.use('/v1', routesApi());
Though you can avoid this altogether by changing your api.js to look like this:
var express = require('express');
var router = express.Router();
router.post('/test', function(req, res){
res.status(200).send({"message" : "OK"});
});
module.exports = router;
and the code for the server can stay the same since now, you're exporting an instance of the Router module.
you have define global variable for app and may use like this:
api.js
exports.allRoutes=function() {
var version1="v1";
app.post('/'+version1+'/test', function(req, res){
res.status(200).send({"message" : "OK"});
});
}
app.js
global.app = express();
var all_routes = require('./server/routes/api');
all_routes.allRoutes();
var server = http.createServer(app);
server.listen(app.get('port'), function(req,res){
console.log('Express server listening on port ' + app.get('port'));
});
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);