使用Express路由处理请求参数中的斜杠字符 [英] Dealing with slash characters in request parameter using Express route

查看:40
本文介绍了使用Express路由处理请求参数中的斜杠字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Express开发URL缩短应用程序.我希望用户能够输入如下网址:

I'm currently working on a URL shortener app using Express. I want the user to be able to enter a URL like this:

https://www.exampleurlshortener.com/new/https://www.google.com

问题是,每当我尝试使用Express指定参数时,它只会提取"https:"部分,此后的所有内容都会丢失,因为2个反斜杠正在注册为新路由:

The problem is whenever I try to specify the parameter using Express it will only extract the 'https:' section and everything after that is lost because the 2 backslashes are registering as a new route:

app.get('/new/:url', (req, res) => {
  console.log(req.params.url) // outputs 'https:'

我考虑过将每个节指定为新参数,但是如果 inner 为空白,则最终会抛出404.我需要使用此方法检查inner是否为空白,否则用户将能够键入 https:/something/www.google.com

I thought about specifying each section as a new parameter but if inner is blank this ends up throwing a 404. I would need to check if inner is blank using this method otherwise the user would be able to type https:/something/www.google.com

app.get('/new/:prot/:inner/:address', (req, res) => {
  // throws 404 on valid addresses

是否有一种简单的方法可以解决我所缺少的问题?是否可以在请求中的某个位置检查完整的URL?还是参数可以忽略反斜杠?

Is there a simple way to solve this that I'm missing? Is the full URL available to be checked somewhere in the request? Or can parameters ignore backslashes?

推荐答案

您可以使用的表达式:

app.get('/new/:url(.*)', (req, res) => {
  console.log(req.params.url) // will output 'https://www.google.com'

这篇关于使用Express路由处理请求参数中的斜杠字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆