如何使用参数和正则表达式创建 KOA 路由
How to create KOA route with both parameter and regex
如何完成以下 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) {
...
}
我正在考虑在路由中使用正则表达式,但我从未看到它如何与 :param 混合使用。
注意:我需要保留该路径语法,因为它已经如上所述进行了 SEO 和索引。
最坏的情况可能是我最终将整个名称作为参数并在单个 handlerFn 中处理它并测试结尾到 _metro 或 _county 或 _city
正则表达式捕获组
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);
如何完成以下 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) {
...
}
我正在考虑在路由中使用正则表达式,但我从未看到它如何与 :param 混合使用。
注意:我需要保留该路径语法,因为它已经如上所述进行了 SEO 和索引。
最坏的情况可能是我最终将整个名称作为参数并在单个 handlerFn 中处理它并测试结尾到 _metro 或 _county 或 _city
正则表达式捕获组
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);