node.js中的自定义迷你路由器

时间:2016-07-11 08:16:51

标签: node.js express router

我要实现一个自定义的迷你路由器,并一直在寻找明确的灵感。

任何人都可以指导我快递js创建路线处理程序。

例如,如何实施以下内容?

节点服务器代码

http.createServer(function (req, res) { //how routing is done after?
    //req???
    req.get("/customers", function(){}) 
    req.get("/customers/:id", function(){})
}).listen(9615);

是使用正则表达式表达js吗?还请指向github存储库中的正确脚本。

3 个答案:

答案 0 :(得分:1)

您需要查看此https://github.com/expressjs/express/blob/master/lib/router/index.js。这是一个用于路由的快速单独模块,您可以将其用于个人用途,而无需重新设置轮子。

[编辑] - 了解如何做到这一点。

var routes = [];
var app = {};
app.get = function(pattern, cb) {
    var splits = pattern.split("/");
    var route = "";
    var regex = "";
    for(i=0; i < splits.length; i++) {
        if (splits[i].indexOf(':') === -1) {
            route += splits[i]+"/";
        } else {
            regex = splits[i].replace(":", "");
        }
    }
    routes.push({ route : routes, regex : regex, cb: cb });
}

app.get("/customers", callback);

.
.
.
// handle incoming request. requestPath comes from server
var requestPath = "/customers"; // example only.

app.handleRequest(requestPath) {
    for(i = 0; i < routes.length; i++) {
        if(routes[i].route === requestPath) {
             cb = routes[i].cb;
        }
    }
    cb();
}

答案 1 :(得分:1)

感谢robertklep

引擎盖表示js使用path-to-regexp

我还从他们的页面找到了正则表达式,快递js使用它来解析URL link

/^(?:\/(?=$))?$/i

当我想要的只是一个基本的路由器而没有得到整个框架以及它在我的项目中的所有依赖项时,没有太多重新发明这里所涉及的轮子。

答案 2 :(得分:0)

请查看the Express JS documentation。它几乎就是这样。例如,使用Express JS的一段代码:

// GET method route
app.get('/', function (req, res) {
    res.send('GET request to the homepage');
});

// POST method route
app.post('/', function (req, res) {
    res.send('POST request to the homepage');
});

对于正则表达式,是的,您可以使用它们。例如:

app.get('/ab(cd)?e', function(req, res) {
    res.send('ab(cd)?e');
});

除此之外,请查看the Express JS GitHub repository中的一个示例。

对于Express JS中的Router实现,请查看their GitHub code (router script)

相关问题