I need to load some async config before run my app, something like this:
var express = require('express');
var router = express.Router();
var myModule = require("myModule");
myModule.create().generateModel().then(tagger => {
router.post('/tag', function(req, res, next) {
res.json(tagger.tag(req.body.text));
});
module.exports = router;
});
but this does not work because require is sync. How can I make this work? How can I reutilize "tagger" in other modules?
You don't need to set module.exports asynchronously because you're exporting the router which is already defined synchronously:
var express = require('express');
var router = express.Router();
var myModule = require("myModule");
myModule.create().generateModel().then(tagger => {
router.post('/tag', function(req, res, next) {
res.json(tagger.tag(req.body.text));
});
});
module.exports = router;
Related
I have a Node/Express app that looks like this:
app.use(foo)
...
app.get('/foo/bar', ...)
...
app.get('/index', ...)
And I want to extract the middleware and the routes so that now I can do:
app.use(myMiddlewareAndRoutes)
...
app.get('/index', ...)
So that myMiddlewareAndRoutes adds the middleware foo and the route '/foo/bar' that belongs to it.
How can I do this?
var express = require('express')
var router = express.Router()
// middleware that is specific to this router
router.use(function timeLog (req, res, next) {
console.log('Time: ', Date.now())
next()
})
// define the home page route
router.get('/', function (req, res) {
res.send('Birds home page')
})
// define the about route
router.get('/about', function (req, res) {
res.send('About birds')
})
module.exports = router
var birds = require('./birds')
// ...
app.use('/birds', birds)
//or if you need it on root level
app.use('/', birds)
You want to create a separate Router object then add it as a middleware with the .use() function.
In the foo.js file I'm creating a new router and exporting it:
foo.js
const { Router } = require('express');
const router = Router();
router.get('/bar', (req, res, next) => {
return res.send('bar');
});
module.exports = router;
Then importing it in the index.js file to add it as a middleware:
index.js
const express = require('express');
const foo = require('./foo.js');
const app = express();
app.use('/foo', foo);
app.get('/index', ...)
Now every route you define in foo.js will use the /foo prefix like /foo/bar.
I would like to make multiple router settings like the example in ExpressJS Doc.
I have index.js , api1 , api2 like below.
How can I pass the db object from index.js to api1 and api2?
I try with
app.use('/api/v1', require('./controllers/api_v1')(db));
but it shows errors:Router.use() requires a middleware function but got a Object
index.js:
var express = require('../..');
const knex = require('knex');
const config = require('./config');
var app = module.exports = express();
const db = knex(config.db);
app.use('/api/v1', require('./controllers/api_v1'));
app.use('/api/v2', require('./controllers/api_v2'));
app.get('/', function(req, res) {
res.send('Hello from root route.')
});
/* istanbul ignore next */
if (!module.parent) {
app.listen(3000);
console.log('Express started on port 3000');
}
api_v1.js
var express = require('../../..');
var apiv1 = express.Router();
apiv1.get('/', function(req, res) {
res.send('Hello from APIv1 root route.');
});
apiv1.get('/users', function(req, res) {
res.send('List of APIv1 users.');
});
module.exports = apiv1;
api_v2.js
var express = require('../../..');
var apiv2 = express.Router();
apiv2.get('/', function(req, res) {
res.send('Hello from APIv2 root route.');
});
apiv2.get('/users', function(req, res) {
res.send('List of APIv2 users.');
});
module.exports = apiv2;
You could export the db object from a database.js file and require it in the index.js file as well as every other file where you need database access. Or, an easier but uglier method, would be to make the variable global via global.db = db. You could then use db everywhere in your Node.JS application.
I have the following snippet of code and when I access the local host I get an error: Cannot GET /
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.send("function has started");
});
express().listen(3001);
module.exports = router;
var express = require('express')
var app = express()
app.get('/', function (req, res) {
res.send('GET request to the homepage')
})
app.listen(3001)
This should be fine
If you want to use the router, you need to use the use method example (app.use('/', router):
var express = require('express');
var router = express.Router();
var app = express()
/* GET home page. */
router.get('/', function (req, res, next) {
res.send("function has started");
});
app.use('/', router)
app.listen(3001);
The express generator creates an app like this:
in the main app.js:
var app = express();
//...
var routes = require('./routes/index');
app.use('/', routes);
//...
in routes/index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
What is the best way to use variables that I define in app.js in the index.js?
For example, before defining the routes, I set up the mongoose model:
var myModel;
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.once('open', function (callback) {
//load schemas
var dbSchema = require('./schema');
myModel = mongoose.model('mymodel', dbSchema.myModel);
});
How can I use 'myModel' in the routes module?
You should define your models outside app.js, in their own separate files for each separate model, and export that model which you can then require in various places you need it. Your model definition doesn't actually need to be inside db.once('open'
For example: if you have a model User you should define it in its own file like this:
db/user.js
var mongoose = require('mongoose');
var schema = mongoose.Schema({
…
});
var model = mongoose.model('user', schema);
module.exports = model;
This way if you want to use the User model inside your routes/index.js:
…
var User = require('../db/user');
router.get('/user/:id', function(req, res, next) {
User.findById(req.params.id, function(err, user){
res.render('user', { title: 'Express', user: user});
});
});
Pass it as a parameter when you require your router in your app.js file. You're going to have to slightly modify your index.js file
var express = require('express');
var myRouter = function(myModel) {
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
// You can use your myModel model here
return router;
}
module.exports = myRouter
Now inside your app.js
var app = express();
//...
// Pass myModel as a parameter
var routes = require('./routes/index')(myModel);
app.use('/', routes);
//...
I want to use code from one module in another module.
Module1Directory has the following files:
Module1.js
exports.create = function(req, res) {
function something(){}
}
Index.js:
'use strict';
var express = require('express');
var controller = require('./Module1.js');
var router = express.Router();
router.post('/', controller.create);
module.exports = router;
Module2Directory has the following files:
Module2.js
var confusing = require('../Module1Directory/Module1.js');
exports.create = function(req, res){
confusing.create.something();
}
Index.js:
'use strict';
var express = require('express');
var controller = require('./Module2.js');
var router = express.Router();
router.post('/', controller.create);
module.exports = router;
the function something run in Module2 returns 'undefined is not a function' in the terminal. What's wrong?
Your create is a function, but you're treating it as a non-function object. You'd have to call it, and it would have to return an object with a something property:
Module1.js:
exports.create = function(req, res) {
function something(){}
return {something: something}; // <===
};
Module2.js
var confusing = require('../Module1Directory/Module1.js');
exports.create = function(req, res){
confusing.create(req, res).something();
// ^^^^^^^^^^
};