Include a module for all routes at express.js 4

时光怂恿深爱的人放手 提交于 2020-01-24 10:59:07

问题


I'm using Express 4.2.0

Is it possible to include a module only once in app.js and use it in any defined route?

Right now this won't work:

app.js

//..
var request = require('request');

var routes = require('./routes/index');
var users = require('./routes/users');

app.use('/', routes);
app.use('/users', users);
//...


routes/user.js

var express = require('express');
var router = express.Router();

router.get('/add', function(req, res) {
    var session = req.session;
    request('http://localhost:8181/Test?val1=getDepartments', function (error, response, body) {
       //...
    });

    res.render('users/add');
});

module.exports = router;

It will say that "request" is not defined in routes/user.js

ReferenceError: request is not defined at Object.module.exports [as handle] (C:\inetpub\wwwroot\node7\routes\users. js:12:5)

Having to include modules in every route which wants to use them doesn't sound like a proper solution...


回答1:


Yes, there are two ways of creating global variables in Node.js, one using the global object, and the other using module.exports

Here is how,

Method 1. Declare variable without var keyword. Just like importModName = require('modxyz') and it will be stored in global object so you can use it anywhere like global.importModName

Method 2. Using exports option. var importModName = require('modxyz'); module.exports = importModName ; and you can use it in other modules.

Look here for somemore explanation http://www.hacksparrow.com/global-variables-in-node-js.html




回答2:


You can leave out the var and do just request = require('request'); but this is frowned upon.

Node.js caches modules. The standard approach is to require modules where needed.



来源:https://stackoverflow.com/questions/25937727/include-a-module-for-all-routes-at-express-js-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!