Node.js 节点JS路径检查器
我想检查一个字符串(类似URL路径)是否在路径数组中。 大概是这样的: 我有一个有效路径列表Node.js 节点JS路径检查器,node.js,regex,Node.js,Regex,我想检查一个字符串(类似URL路径)是否在路径数组中。 大概是这样的: 我有一个有效路径列表 const allowedPaths = [ { path: `/resource/:objectid/property`, method: callFunction1 }, { path: `/another-resource/:objectid/property`, method: callFunction2 }] 如果我得到这个/resource/1/property我想调用f
const allowedPaths = [
{
path: `/resource/:objectid/property`,
method: callFunction1
},
{
path: `/another-resource/:objectid/property`,
method: callFunction2
}]
如果我得到这个/resource/1/property
我想调用function1,因为路径类似于第一个对象
谢谢 您基本上需要一个正则表达式来解析,只要它匹配,就使用tat对象来调用函数。有一些包可用于执行此任务。其中之一是regexp的路径。代码如下所示
const {pathToRegexp} = require("path-to-regexp");
const allowedPaths = [
{
path: "/resource/:objectid/property",
method: () => {console.log("firstFunction....")}
},
{
path: "/another-resource/:objectid/property",
method: () => {console.log("secondFunction....")}
}];
function getFunction(path) {
const item = allowedPaths.find(row => pathToRegexp(row.path).exec(path) != null);
if (item) {
return item.method;
}
return null;
}
getFunction('/resource/1/property')();
getFunction('/another-resource/1/property')();
你也可以在这里试试
我认为这很容易,但也许我没有正确理解这个问题:
function testPath(inputURL) {
let elems = inputURL.split(path.sep)
allowedPaths.forEach(function(aPath) {
let subjPath = aPath.path.split(path.sep)
elems.forEach(function(elem, index) {
if (subjPath[index] !== elem && elem.charAt(0) !== ":") {
break
else if (elem.charAt(0) !== ":") {
break
}
return aPath.method()
})
})
}
听起来像是一份工作,在那里你可以使用正确的工具。我个人认为你的问题措辞没有意义,你的意思是测试输入字符串是否是一个有效的(可识别的格式)URL吗?如果字符串满足路径期望(在示例中是/resource/:objectid/property),它应该调用一个函数。。。我的想法是基于路径创建一个API代理,所以您需要这样:
函数testPath(inputURL){//code以查看是否在'allowedPaths'中输入格式)}
不用说,您可能需要执行一些类似charm的null检查!!谢谢我错过什么了吗?