我已经创建了一个简单的小路径解析函数,这样我就可以保持我的代码干净并且易于维护,这是在应用程序启动并运行并解析config.json相应方法和请求路径时运行的小函数:
const fs = require('fs');
const path = require('path');
module.exports = function(app, root) {
fs.readdirSync(root).forEach((file) => {
let dir = path.resolve(root, file);
let stats = fs.lstatSync(dir);
if (stats.isDirectory()) {
let conf = require(dir + '/config.json');
conf.name = file;
conf.directory = dir;
if (conf.routes) route(app, conf);
}
})
}
function route(app, conf) {
let mod = require(conf.directory);
for (let key in conf.routes) {
let prop = conf.routes[key];
let method = key.split(' ')[0];
let path = key.split(' ')[1];
let fn = mod[prop];
if (!fn) throw new Error(conf.name + ': exports.' + prop + ' is not defined');
if (Array.isArray(fn)) {
app[method.toLowerCase()].apply(this, path, fn);
} else {
app[method.toLowerCase()](path, fn);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我遇到的问题是有时我需要将多个参数传递给快速路由器,例如在使用这样的护照的情况下:
exports.authSteam = [
passport.authenticate('facebook', { failureRedirect: '/' }),
function(req, res) {
res.redirect("/");
}
];
Run Code Online (Sandbox Code Playgroud)
所以我想我可以将它们作为数组传递,然后适当地将它们解析到路由器中,我的配置例如如下所示:
{
"name": "Routes for the authentication",
"description": "Handles the authentication",
"routes": {
"GET /auth/facebook": "authFacebook",
"GET /auth/facebook/return": "authFacebookReturn"
}
}
Run Code Online (Sandbox Code Playgroud)
唯一的问题是我收到此错误:
app[method.toLowerCase()].apply(this, path, fn);
^
TypeError: CreateListFromArrayLike called on non-object
Run Code Online (Sandbox Code Playgroud)
如果我,console.log(fn)我明白了[ [Function: authenticate], [Function] ]
我不确定我做错了什么,任何信息都会非常感谢.
| 归档时间: |
|
| 查看次数: |
25535 次 |
| 最近记录: |