var express = require('express');
var exampleRouter = express.Router();
exampleRouter.get([
'/example/cat/:id/subcat/:subId', /*1st URL*/
'/example/:id/:subId/', /*2nd URL*/
],function(req, res){
if( *1st url condition*){ // It should enter here
/*do something..*/
}else if( *2nd url condition* ){
/*do something..*/
}
});
假设来自浏览器的请求是这样的 http://www.example.com/example/cat/1/subcat/2
第一个Url条件应该是什么?
答案 0 :(得分:0)
您可以使用originalUrl或path:
console.log(req.originalUrl)
在你的情况下(试试):
var express = require('express');
var exampleRouter = express.Router();
projectRouter.get([
'/example/cat/:id/subcat/:subId', /*1st URL*/
'/example/:id/:subId/', /*2nd URL*/
],function(req, res){
if(req.url == "/example/cat/:id/subcat/:subId"){
// It should enter here do something..*/
} else if(req.url == "/example/:id/:subId/"){
// do something..
}
});
或(更干净):
var express = require('express');
var exampleRouter = express.Router();
projectRouter.get('/example/cat/:id/subcat/:subId',function(req, res){
// It should enter here do something..
});
projectRouter.get('/example/:id/:subId/',function(req, res){
// Second route
});
第二种方式更常见。
答案 1 :(得分:0)
这样的事情可能有用......
projectRouter.get([
'/example/cat/:id/subcat/:subId', /*1st URL*/
'/example/:id/:subId/', /*2nd URL*/
],function(req, res){
var param = req.url.replace(/^\/|\/$/g, '').split('/');
if(param[1] == "cat" && param[3] == "subcat"){
// It should enter here do something..*/
} else {
// do something..
}
});