我正在尝试在我的快递应用中添加新路线,但在尝试启动服务器时我一直收到错误。错误是
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]
这是我的文件,我是节点的新手,所以如果我遗漏了一个重要文件,请告诉我
路由/ furniture.js
exports.furniture = function(req, res){
res.render('furniture', { title: '4\267pli' });
};
路由/ index.js
/*
* GET home page.
*/
exports.index = function(req, res){
res.render('index', { title: '4\267pli' });
};
视图/ 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
/**
* 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'));
});
答案 0 :(得分:25)
问题是:
routes = require('./routes'),
user = require('./routes/user'),
furniture = require('./routes/furniture'),
这三个是设置您的路径文件夹,而不是特定文件,快递将查找index.js(未找到,然后 - &gt;错误)
在这些文件夹中,您应该将index.js与您的:
放在一起exports.xxxx = function(req, res){
res.render('xx', { foo: foo});
};
然后,您的项目文件夹结构应如下所示:
routes/
├── index.js
│
├── user/
│ └── index.js (with a exports.user inside)
│
└── fourniture/
└── index.js (with a exports.furniture inside)
您可以将多个导出功能添加到以下路线中:
app.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
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 });
};
答案 1 :(得分:6)
如果您的网站有时太大,我宁愿做类似的事情:
routes/furniture.js
:
module.exports = function(app)
{
app.get("/furniture/", function(req, res) {
res.render('furniture', { title: '4\267plieee' });
});
}
然后在app.js
:
require("./routes/furniture")(app);
它主要是相同的,但app.js会更干净。
答案 2 :(得分:2)
虽然这有点旧,但分享我这样做的方式。这是另一种方法,它使代码更清晰,更容易添加路径。
<强> app.js 强>
const app = express();
const routes = require('./routes');
app.use('/api', routes); //Main entry point
<强> /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;
&#39;的ValidateUser&#39;和&#39; validateAdmin&#39;是自定义中间件,用于验证请求参数或在请求到达实际请求处理程序之前进行一些预处理。这是可选的,您也可以拥有多个中间件(逗号分隔)。
<强> /routes/user.js 强>
module.exports = {
createUser:function(req,res,next){
},
updateUser:function(req,res,next){
},
deleteUser:function(req,res,next){
}
}
<强> /routes/admin.js 强>
module.exports = {
getDashboard:function(req,res,next){
}
}
答案 3 :(得分:1)
然后再也不会回头。在其他重要内容上节省时间。
$ npm install express-routemagic --save
const magic = require('express-routemagic')
magic.use(app, __dirname, '[your route directory]')
就是这样!
project_folder
|--- routes
| |--- nested-folder
| | |--- index.js
| |--- a-file-that-doesnt-share-same-name-with-another-folder.js
| |--- index.js
|--- app.js
const express = require('express')
const app = express()
const magic = require('express-routemagic')
magic.use(app, __dirname, 'routes')
const router = require('express').Router()
router.get('/', (req, res) => { ... })
router.get('/something-else', (req, res) => { ... })
通常,您可能要启动一个文件夹并使用
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) => { ... })
免责声明:我写了包裹。但这确实是早该完成的工作,已经等到有人写了。