In my express app I have a router listening to api/shorten/
:
router.get('api/shorten/:longUrl', function(req, res, next) {
console.log(req.params.longUrl);
}
When I use something like:
http://localhost:3000/api/shorten/www.udemy
I get www.udemy
which is what I expect.
But when I use:
http://localhost:3000/api/shorten/
I get a 404 error.
I want to get when I access
req.params.parameter
.
In my express app I have a router listening to api/shorten/
:
router.get('api/shorten/:longUrl', function(req, res, next) {
console.log(req.params.longUrl);
}
When I use something like:
http://localhost:3000/api/shorten/www.udemy.com
I get www.udemy.com
which is what I expect.
But when I use:
http://localhost:3000/api/shorten/http://www.udemy.com
I get a 404 error.
I want to get http://www.udemy.com
when I access req.params.parameter
.
4 Answers
Reset to default 22I'm not sure if you're still looking for a solution to this problem. Perhaps just in case someone else is trying to figure out the same thing, this is a simple solution to your problem:
app.get('/new/*', function(req, res) {
// Grab params that are attached on the end of the /new/ route
var url = req.params[0];
This way you don't have to sweat about any forward slashes being mistaken for routes or directories, it will grab everything after /new/.
You need to use encodeURIComponent
in the client, and decodeURIComponent
in the express server, this will encode all the not allowed characters from the url parameter like :
and /
You need to escape as so:
escape("http://www.google.com")
Which returns:
"http%3A//www.google.com"
I just want to add that if you pass another params like ?param=some_param
into your "url paramter" it will not show up in req.params[0]
.
Instead you can just use req.url
property.
:
are not allowed anywhere except in the protocol so can't be used in the path of the URL. – jfriend00 Commented Mar 24, 2017 at 19:50:
character must be encoded when it appears anywhere other than in the first protocol. See section 2.2. of the RFC. – jfriend00 Commented Mar 24, 2017 at 20:21