ExpressJS Route Parameter with Slash

2019-04-01 17:00发布

问题:

Im using ExpressJS. I want pass url as parameter.

app.get('/s/:url', function(req, res) {
    console.log(req.params.url);
});

/s/sg.com                   //sg.com
/s/www.sg.com               //www.sg.com
/s/http://sg.com            //http://sg.com
/s/http://sg.com/folder     //http://sg.com/folder

How to correct the route such that everything afterr /s/ will be considered as paramenter including slashes.

Thanks

回答1:

Uh, if you want to stick a URL inside of another URL, you need to URLencode it. If you want to stick one in their raw and suffer the consequences, just use app.get('/s/*'... and then manually parse out the url with req.url.slice(3). But hear me know and believe me later, URL Encoding is the right way to do this via the encodeURIComponent that is built in to JavaScript and works in both the browser and node.js.