首页 > 解决方案 > Javascript 仅允许 URL 参数的白名单

问题描述

我正在尝试创建一个允许的 url 参数/查询字符串的白名单,以便从 url 中删除 url 中不在我的白名单中的任何提供的 args。

这是我的代码。

var paramsString = "2=lol&q=how&44=slap&topic=api&1=tr&view=media"; //test url args
var searchParams = new URLSearchParams(paramsString);

//this whitelist of args are the only args to be allowed in the url
var url_args_whitelist = [
"beforeafter",
"catid",
"childforums",
"display",
"element_id",
"element_type",
"exactname",
"filter_mediaType",
"filter_order",
"filter_order_Dir",
"filter_search",
"filter_tag",
"format",
"id",
"Itemid",
"layout",
"limit",
"limitstart",
"messageid",
"more",
"option",
"order",
"ordering",
"quality",
"query",
"recently",
"recip",
"reply_id",
"return",
"searchdate",
"searchf",
"searchphrase",
"searchuser",
"searchword",
"sortby",
"start",
"task",
"tmpl",
"token",
"view"
];

for (let p of searchParams) {
//if the url argument is not in our whitelist of allowed arguments then delete it
  searchParams.delete(p[0]);
}

console.log("whitelist output: ", searchParams.toString() );

如何让我的代码检查我的白名单,然后运行我的删除功能来删除垃圾 url 参数。

标签: javascript

解决方案


解释

好的,这是一个非常简单的实现,使用reduce函数,它简单、干净,如果有的话,由于使用了这种方法,它不会导致值的searchParams变化。

此外,我想补充一点,我试图尽可能少地进行更改,我假设您不希望代码中出现副作用。

编辑

如果你想了解我提供的 ES6 风格的实现,那么你可以更多地研究诸如currying之类的主题,对于这个主题,我特别建议阅读Eric Elliott制作的一些内容,最后如果你想了解更多关于箭头函数等语法,我可能会建议MDN

var paramsString = "2=lol&q=how&44=slap&topic=api&1=tr&view=media"; //test url args
var searchParams = new URLSearchParams(paramsString);

// This whitelist of args are the only args to be allowed in the url.
var url_args_whitelist = [
  "beforeafter", "catid", "childforums", "display", "element_id",
  "element_type", "exactname", "filter_mediaType", "filter_order",
  "filter_order_Dir", "filter_search", "filter_tag", "format", "id",
  "Itemid", "layout", "limit", "limitstart", "messageid", "more",
  "option", "order", "ordering", "quality", "query", "recently",
  "recip", "reply_id", "return", "searchdate", "searchf", "searchphrase",
  "searchuser", "searchword", "sortby", "start", "task", "tmpl", "token", "view"
];

// Create an Array from searchParams, then reduce it via ensuring that each 
// key exists within the 'url_args_whitelist' Array, finally joining using 
// an '&' symbol. 
var cleanURL = Array.from(searchParams).reduce(function(array, sub) {
  var key = sub[0], value = sub[1];

  // Check the argument exists in the URL, if so, then push it onto the new array.
  if (url_args_whitelist.indexOf(key) > -1) array.push(key + '=' + value);

  return array;
}, []).join("&");

// Finally a more ES6 style approach, basically a one liner.
const clean = a => l => a.filter(o => l.includes(o[0])).map(o => o.join("=")).join("&");

// Results.
console.log("whitelist output:", cleanURL);
console.log("es6 output:", clean(Array.from(searchParams))(url_args_whitelist));
console.log("old output:", searchParams.toString());


推荐阅读