在express.js 4包含所有路由的模块 [英] Include a module for all routes at express.js 4

查看:75
本文介绍了在express.js 4包含所有路由的模块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Express 4.2.0

I'm using Express 4.2.0

是否可以在app.js中仅包含一个模块一次,并在任何已定义的路由中使用它?

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

现在这行不通:

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;

它将说routes/user.js

ReferenceError:请求未定义 在Object.module.exports [作为句柄](C:\ inetpub \ wwwroot \ node7 \ routes \ users. js:12:5)

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...

推荐答案

是的,有两种方法可以在Node.js中创建全局变量,一种使用global object,另一种使用module.exports

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

这是怎么回事,

方法1.声明不带var关键字的变量.就像importModName = require('modxyz')一样,它将存储在全局对象中,因此您可以在global.importModName

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

方法2.使用导出选项. var importModName = require('modxyz'); module.exports = importModName ;,您可以在其他模块中使用它.

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

在此处查看更多说明 http://www.hacksparrow.com /global-variables-in-node-js.html

这篇关于在express.js 4包含所有路由的模块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆