在节点express中的URL参数重写

每当标签提交空格时,空格在响应中显示为%20。 我将如何重写每个空间,以便在请求和响应中可以是短划线? 有没有可靠的图书馆? 谢谢!

路线

router.get('/search/:tag', function(req, res) { const tag = req.params.tag; tag.toLowerCase(); shopify.article.list(86289414) .then(function (response) { response.reverse(); response = response.map(function(element) { return { author: element.author, blog_id: element.blog_id, body_html: element.body_html, created_at: element.created_at, handle: element.handle, id: element.id, image: element.image, published_at: element.published_at, summary_html: element.summary_html, tags: element.tags.toString().toLowerCase(), template_suffix: element.template_suffix, title: element.title, updated_at: element.updated_at, user_id: element.user_id } }) response = response.filter(function(item) { return item.tags.indexOf(tag) > -1; }); var data = { articles: response.map((article) => { return { author: article.author, id: article.id, html: article.body_html, tags: article.tags.split(","), date: moment(article.published_at).format("Do MMM YYYY"), slug: article.handle, title: article.title, } // return }) // map } // data console.log(data); res.render('blog-tags' , data); }) // then .catch(err => console.log(err) ) }); 

首先这不会做你所期望的:

 tag.toLowerCase(); 

你需要使用:

 tag = tag.toLowerCase(); 

如果你想要tagvariables的值改变。

这是因为JavaScript中的string是不可变的,没有操作可以改变string,所以只能用新stringreplacevariables的值。 像.toLowerCase()方法总是返回一个新的string。

现在,如果你的variables已经包含'%20'等,那么你需要使用:

 tag = decodeURIComponent(tag); 

但请注意,这可能已经由框架处理。

现在,要将空格更改为下划线,请使用:

 tag = tag.replace(/ /g, '_'); 

你可以把所有这些结合起来:

 tag = decodeURIComponent(tag).toLowerCase().replace(/ /g, '_'); 

或者如果你的variables已经包含解码的string:

 tag = tag.toLowerCase().replace(/ /g, '_'); 

例:

 let tag = 'Aaa%20BbB%20cCC'; tag = decodeURIComponent(tag).toLowerCase().replace(/ /g, '_'); console.log(tag); // prints: aaa_bbb_ccc