Javascript Node.js:不同文件中的配置和路由
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8438998/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js: Configuration and routes in a different file
提问by donald
I am starting a new Node.js app and this time, I'm trying to organize the code correctly instead of having everything in the same file.
我正在启动一个新的 Node.js 应用程序,这一次,我试图正确组织代码,而不是将所有内容都放在同一个文件中。
I only have a simple setup now at server.coffee
:
我现在只有一个简单的设置server.coffee
:
express = require 'express'
app = module.exports = express.createServer()
## CONFIGURATION ##
app.configure () ->
app.set 'views', __dirname + '/views'
app.set 'view engine', 'jade'
app.use express.bodyParser()
app.use express.logger('dev')
app.use express.profiler()
app.use express.methodOverride()
app.use app.router
app.use express.static(__dirname + '/public')
app.configure 'development', () ->
app.use express.errorHandler({dumpExceptions: true, showStack: true})
app.configure 'production', () ->
app.use express.errorHandler()
app.get '/', (req,res) ->
res.render 'index'
title: 'Express'
## SERVER ##
port = process.env.PORT || 3000
app.listen port, () ->
console.log "Listening on port" + port
I have some questions regarding that simple code and I know that all the answers depend on the developer but I really want to do it right:
我对那个简单的代码有一些疑问,我知道所有的答案都取决于开发人员,但我真的很想把它做对:
- Should the
server.js
file have more than theapp.listen
? What should be there exactly? - Shouldn't all the configurations be in a different file than the routes? How can I remove the
app.get
to other file and make them work when I run theserver.coffee
? - What exactly should contain the
index.coffee
that I see in a lot of apps like Hubot?
server.js
文件应该多于app.listen
? 究竟应该有什么?- 不应该所有配置都在与路由不同的文件中吗?如何
app.get
在运行时删除到其他文件并使它们工作server.coffee
? index.coffee
我在 Hubot 等许多应用程序中看到的内容究竟应该包含哪些内容?
I hope someone can give me an answer other than "it depends".
我希望有人能给我一个答案而不是“这取决于”。
回答by Dominic Barnes
You can leverage require
, and simply pass the app
var in as a parameter to a method. It's not the prettiest syntax, nor is it in CoffeeScript, but you should get the idea.
您可以利用require
,只需将app
var 作为参数传递给方法。这不是最漂亮的语法,在 CoffeeScript 中也不是,但您应该明白这一点。
routes.js
路由.js
module.exports = function (app) {
// set up the routes themselves
app.get("/", function (req, res) {
// do stuff
});
};
app.js
应用程序.js
require("./routes")(app);
If you want to take it a step further, I separate my routes into smaller groups, and in it's own subfolder. (like: routes/auth.js
for login/logout, routes/main.js
for home/about/contact and so on)
如果你想更进一步,我会将我的路线分成更小的组,并在它自己的子文件夹中。(例如:routes/auth.js
用于登录/注销,routes/main.js
用于家庭/关于/联系等)
routes/index.js
路线/ index.js
// export a function that accepts `app` as a param
module.exports = function (app) {
require("./main")(app);
// add new lines for each other module, or use an array with a forEach
};
(rename routes.js
from before as routes/main.js
, the source itself remains the same)
(routes.js
从之前重命名为routes/main.js
,源本身保持不变)
回答by Konrad Reiche
Express 4 simplifiesthis with the express.Router
class.
Express 4通过类简化了这一点express.Router
。
The other feature to help organize routes is a new class,
express.Router
, that you can use to create modular mountable route handlers. ARouter
instance is a complete middleware and routing system; for this reason it is often referred to as a “mini-app”.The following example creates a router as a module, loads a middleware in it, defines some routes, and mounts it on a path on the main app.
Create a router file named
birds.js
in the app directory, with the following content:var express = require('express'); var router = express.Router(); // middleware 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;
Then, load the router module in the app:
var birds = require('./birds'); app.use('/birds', birds);
The app will now be able to handle requests to
/birds
and/birds/about
, along with calling thetimeLog
middleware specific to the route.
帮助组织路由的另一个功能是一个新类 ,
express.Router
您可以使用它来创建模块化的可安装路由处理程序。一个Router
实例是一个完整的中间件和路由系统;因此,它通常被称为“迷你应用程序”。下面的示例创建一个路由器作为模块,在其中加载一个中间件,定义一些路由,并将其安装在主应用程序的路径上。
birds.js
在app目录下创建一个router文件,内容如下:var express = require('express'); var router = express.Router(); // middleware 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);
该应用程序现在将能够处理对
/birds
和 的请求/birds/about
,以及调用timeLog
特定于路由的中间件。
回答by alessioalex
There are 2 similar question that can help you a lot with this:
有 2 个类似的问题可以帮助您解决这个问题:
How to structure a express.js application?