node.js 向 node express 添加新路由
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16548586/
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
adding a new route to node express
提问by Antarr Byrd
I'm trying to add a new route in my express app but I keep getting error when trying to start the server. The error is
我正在尝试在我的 Express 应用程序中添加一条新路由,但在尝试启动服务器时我不断收到错误消息。错误是
C:\development\node\express_app\node_modules\express\lib\router\index.js:252
throw new Error(msg);
^
Error: .get() requires callback functions but got a [object Undefined]
here are my files, I'm new to node so let me know if i left out an important file
这是我的文件,我是 node 的新手,所以如果我遗漏了一个重要文件,请告诉我
routes/furniture.js
路线/家具.js
exports.furniture = function(req, res){
res.render('furniture', { title: '47pli' });
};
routes/index.js
路线/ index.js
/*
* GET home page.
*/
exports.index = function(req, res){
res.render('index', { title: '47pli' });
};
views/furniture.ejs
意见/furniture.ejs
<!DOCTYPE html>
<html>
<head>
<title>4·pli -- architecture</title>
<link rel='stylesheet' href='/stylesheets/style.css'/>
<link href='http://fonts.googleapis.com/css?family=Didact+Gothic' rel='stylesheet' type='text/css'>
</head>
<body>
<div class="wrapper">
<h1 class="logo"><%= title %></h1>
</div>
</body>
</html>
app.js
应用程序.js
/**
* Module dependencies.
*/
var express = require('express')
, routes = require('./routes')
, user = require('./routes/user')
, furniture = require('./routes/furniture')
, http = require('http')
, path = require('path');
var app = express();
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
app.get('/', routes.index);
app.get('/users', user.list);
app.get('/furniture', routes.furniture);
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
回答by jmingov
The trouble is:
麻烦在于:
routes = require('./routes'),
user = require('./routes/user'),
furniture = require('./routes/furniture'),
These 3 are setting your routes folders, not a specific file, express will look for a index.js ( not found, then --> error)
这 3 个是设置你的路由文件夹,而不是一个特定的文件,express 会寻找一个 index.js(没有找到,然后 --> 错误)
Inside these folders, you should put a index.js with your:
在这些文件夹中,您应该将 index.js 与您的:
exports.xxxx = function(req, res){
res.render('xx', { foo: foo});
};
Then, your project folder structure should look like:
然后,您的项目文件夹结构应如下所示:
routes/
├── index.js
│
├── user/
│ └── index.js (with a exports.user inside)
│
└── fourniture/
└── index.js (with a exports.furniture inside)
You can add multiple export functionsto a route like these:
您可以向路由添加多个导出功能,如下所示:
app.js
应用程序.js
// a folder called routes with the index.js file inside
routes = require('./routes')
.
.
.
app.get('/', routes.main_function);
app.get('/sec_route', routes.sec_function);
app.post('/other_route', routes.other_function);
/routes/index.js
/routes/index.js
exports.main_function = function(req, res){
res.render('template1', { foo: foo });
};
exports.sec_function = function(req, res){
res.render('template2', { bar: bar });
};
exports.other_function = function(req, res){
res.render('template1', { baz: baz });
};
回答by fritsMaister
If your website is so big some times I prefer to do something like:
如果您的网站有时非常大,我更喜欢执行以下操作:
routes/furniture.js:
routes/furniture.js:
module.exports = function(app)
{
app.get("/furniture/", function(req, res) {
res.render('furniture', { title: '47plieee' });
});
}
And then in app.js:
然后在app.js:
require("./routes/furniture")(app);
It's mainly the same but app.js will be cleaner.
它主要是相同的,但 app.js 会更干净。
回答by aravindaM
Although this is somewhat old, though of sharing the way i do this. Here is a another approach which makes code more cleaner and easy to add routes.
虽然这有点旧,但分享我这样做的方式。这是另一种使代码更简洁、更容易添加路由的方法。
app.js
应用程序.js
const app = express();
const routes = require('./routes');
app.use('/api', routes); //Main entry point
/routes/index.js
/routes/index.js
const router = require('express').Router();
const user = require('./user');
const admin = require('./admin');
//This is a simple route
router.get('/health-check', (req, res) =>
res.send('OK')
);
router.route('/users')
.post(validate, user.createUser);
router.route('/users/:userId')
.get(validateUser, user.getUser)
.patch(validateUser, user.updateUser)
.delete(validateUser, user.deleteUser);
router.route('/admins/:adminId/dashboard')
.get(validateAdmin,admin.getDashboard);
module.exports = router;
'validateUser' and 'validateAdmin' are custom middle wares, which will be used to validates request parameters or to do some pre-processing before request reach the actual request handler. This is optional and you can have multiple middleware (comma separated) as well.
'validateUser' 和 'validateAdmin' 是自定义中间件,它们将用于验证请求参数或在请求到达实际请求处理程序之前进行一些预处理。这是可选的,您也可以有多个中间件(逗号分隔)。
/routes/user.js
/routes/user.js
module.exports = {
createUser:function(req,res,next){
},
updateUser:function(req,res,next){
},
deleteUser:function(req,res,next){
}
}
/routes/admin.js
/routes/admin.js
module.exports = {
getDashboard:function(req,res,next){
}
}
回答by Calvintwr
Follow a simple and consistent folder structure, then use a module to have everything done automatically.
遵循简单一致的文件夹结构,然后使用模块自动完成所有操作。
Then never look back. Spend time saved on the rest of the important stuff.
然后永远不要回头。把节省下来的时间花在剩下的重要事情上。
TL;DR
TL; 博士
$ npm install express-routemagic --save
const magic = require('express-routemagic')
magic.use(app, __dirname, '[your route directory]')
That's it!
就是这样!
More info:
更多信息:
How you would do this? Let's start with file structuring:
你会怎么做?让我们从文件结构开始:
project_folder
|--- routes
| |--- nested-folder
| | |--- index.js
| |--- a-file-that-doesnt-share-same-name-with-another-folder.js
| |--- index.js
|--- app.js
In app.js
在 app.js 中
const express = require('express')
const app = express()
const magic = require('express-routemagic')
magic.use(app, __dirname, 'routes')
In any of your routing files:
在您的任何路由文件中:
For e.g., index.js
例如,index.js
const router = require('express').Router()
router.get('/', (req, res) => { ... })
router.get('/something-else', (req, res) => { ... })
Or a-file-that-doesnt-share-same-name-with-another-folder.js
或 a-file-that-doesnt-share-same-name-with-another-folder.js
Usually you might want to start a folder and use the
index.jspattern. But if it's a small file it's okay.
通常您可能想要启动一个文件夹并使用该
index.js模式。但如果它是一个小文件,那没关系。
const router = require('express').Router()
const dir = 'a-file-that-do-not-have-another-folder-with-same-name' // you can use this to shorten, but it's optional.
router.get(`$(dir)/`, (req, res) => { ... })
router.get(`$(dir)/nested-route`, (req, res) => { ... })
Disclaimer: I wrote the package. But really it's long-overdue, it reached my limit to wait for someone to write it.
免责声明:我写了这个包。不过真的是来晚了,等人来写已经到了极限了。

