gpt4 book ai didi

node.js - Express 如何路由相似的 url 链接?

转载 作者:太空宇宙 更新时间:2023-11-03 21:54:10 31 4
gpt4 key购买 nike

使用 Node.js 和 Express 开发 Web 应用程序。

我有以下两个网址来区分:

  1. /api/v1/source?id=122323
  2. /api/v1/source?timestamp=1555050505&count=10

我想出了一个天真的解决方案。我将类似的 url 留给一种路由方法,并使用 if eles 指定解决方案,即:

if(id){
//solution with id
}

if(timestamp&&count){
//solution with timestamp and count but without id
}

显然,这并不干净。因为将来,我可能想添加新字段,这将使这个路由器又大又丑。

那么我该如何克服这个问题呢?或者改变url结构。我想构建一个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')
}
})()

关于node.js - Express 如何路由相似的 url 链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45265708/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com