【问题标题】:How to create KOA route with both parameter and regex如何使用参数和正则表达式创建 KOA 路由
【发布时间】:2015-03-04 14:12:23
【问题描述】:

如何完成以下 KOA 路由处理程序:

app.get("/Chicago_Metro/Cicero_City", myFunctionHandler1)
app.get("/Cook_County/Cicero_City", myFunctionHandler2)

并以“Chicago”作为要传递给“metro”的参数或传递给县的“Cook”和传递给下面我的处理程序中的“城市”的“Cicero”:

function *myFunctionHandler1(metro, city) {
...
}

function *myFunctionHandler2(county, city) {
...
}

我在路线中考虑使用 Regex,但我从未见过它如何与 :param 混合使用。

注意:我需要保留该路径语法,因为它已经按照上面的方式进行了 SEO 和索引。

最坏的情况可能我会以全名作为参数结束,并在单个 handlerFn 中处理它并测试结尾到 _metro 或 _county 或 _city

【问题讨论】:

    标签: routes koa


    【解决方案1】:

    正则表达式捕获组

    var koa   = require('koa'),
        route = require('koa-router'),
        app   = koa();
    
    app.use(route(app));
    
    app.get(/^\/(.*)(?:_Metro)\/(.*)(?:_City)$/, function *(){
        var metro = this.params[0];
        var city = this.params[1];
        this.body = metro + ' ' + city;
    });
    
    app.get(/^\/(.*)(?:_County)\/(.*)(?:_City)$/, function *(){
        var county = this.params[0];
        var city = this.params[1];
        this.body = county + ' ' + city;
    });
    
    app.listen(3000);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-28
      • 2015-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-25
      • 1970-01-01
      相关资源
      最近更新 更多