如何快递路线类似的url链接?
使用node.js开发web应用程序并进行expression。
我有以下两个url来区分:
- / API / V1 /源?ID = 122323
- / API / V1 /源?时间戳= 1555050505&计数= 10
我想出了一个天真的解决scheme。 我离开这样的类似的URL到一个路线方法,并使用if eles
指定的解决scheme,即:
if(id){ //solution with id } if(timestamp&&count){ //solution with timestamp and count but without id }
显然,这是不干净的。 因为将来我可能要增加新的领域,这将使这个路由器巨大和丑陋。
那么我该如何克服这个问题呢? 或者更改url结构。我想要构build一个Restful api。
尝试将所有属性放在列表中,并使用Array#every
来检查Array中的所有值是否为true。
也许这样的事情:
(( /* req, res */)=>{ // Dummy express Request Object const req = { params : { //id : '123', count : 10, timestamp : 1555050505, newParameter : 'whatever value' } } let { params } = req; let { id , count , timestamp , newParameter } = params; if(id){ console.log('Action with id'); return; } let secondConditionArray = [ count, timestamp, newParameter ]; if( secondConditionArray.every(Boolean) ){ console.log('Second Action') } else { console.log('Some values are no truthy') } })()
您可以使用req.params
获取Url参数
if(req.params.id){ //solution with id } if(req.params.timestamp && req.params.count){ //solution with timestamp and count but without id }