Node 将路由表示为模块:将“require”放在哪里?
Node express routes as modules: where to put `require`s?
Node Express 的 Routing guide 给出了以下将路由创建为模块的示例:
/birds.js:
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
/app.js:
var birds = require('./birds')
// ...
app.use('/birds', birds)
我想知道为什么他们把 birds.js
的前两行放在那里而不是 app.js
。
首先,app.js
调用了app
的一个方法。 app
应该如何定义在 app.js
中?我认为他们(奇怪地)为了教程而忽略了包含必要的代码。
其次,假设我想在名为 dogs.js
的文件中将第二条路线作为模块,用于狗和鸟。它看起来与 birds.js
WRT 前两行相同吗?据我所知,这将导致两个快递实例。 (或者如果 app.js
也需要三个?!)
示例不完整。整个应用程序设置被排除在外(我认为是因为它在文档中有进一步的解释,并被替换为 // ...
)。在您的 app.js 中,您至少需要:
var express = require('express');
var app = express();
bird.js 中的前两行与 app.js 中的两行(缺失的)无关。您需要它们来创建路由器。
关于你的最后一个问题:是的,你会创建另一个路由器,就像 bird 路由器一样。路由器不是快递 app/instance,在您的应用程序中安装多个路由器完全没问题。
Node Express 的 Routing guide 给出了以下将路由创建为模块的示例:
/birds.js:
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
/app.js:
var birds = require('./birds')
// ...
app.use('/birds', birds)
我想知道为什么他们把 birds.js
的前两行放在那里而不是 app.js
。
首先,app.js
调用了app
的一个方法。 app
应该如何定义在 app.js
中?我认为他们(奇怪地)为了教程而忽略了包含必要的代码。
其次,假设我想在名为 dogs.js
的文件中将第二条路线作为模块,用于狗和鸟。它看起来与 birds.js
WRT 前两行相同吗?据我所知,这将导致两个快递实例。 (或者如果 app.js
也需要三个?!)
示例不完整。整个应用程序设置被排除在外(我认为是因为它在文档中有进一步的解释,并被替换为 // ...
)。在您的 app.js 中,您至少需要:
var express = require('express');
var app = express();
bird.js 中的前两行与 app.js 中的两行(缺失的)无关。您需要它们来创建路由器。
关于你的最后一个问题:是的,你会创建另一个路由器,就像 bird 路由器一样。路由器不是快递 app/instance,在您的应用程序中安装多个路由器完全没问题。