Dealing with slash characters in request parameter using Express route

旧街凉风 提交于 2021-02-18 06:40:13

问题


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

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:'

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

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?


回答1:


You can use an expression to for your URL placeholders:

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


来源:https://stackoverflow.com/questions/42351738/dealing-with-slash-characters-in-request-parameter-using-express-route

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!