0

I'm working with Express Router, and I'm trying to get some information from params URL, but I cannot make it works as it always returned me a 404.

This is the URL I'm trying to call

http://localhost:8080/api/v1/contr/method?param1=value1&param2=param2

And in my express router I have:

this.router.get("/contr/method", JWT.authenticateJWT, ContrController.method.bind(ContrController));

And I always get

  finalhandler default 404 +2m

If I send the request without params the app work as expected:

http://localhost:8080/api/v1/contr/method
Faabass
  • 1,394
  • 8
  • 29
  • 58
  • 1
    I don't know if this changes anything, but `this.router.get("contr/method", ...)` should be `this.router.get("/contr/method", ...)` with a leading `/`. Also, please show how the router itself is registered for `/api/v1`. And, are you sure that using a URL without query parameters such as `http://localhost:8080/api/v1/contr/method` works fine? And, are you sure the middleware you're using on that route isn't looking at the query parameters and skipping it? For, far too much code missing here for us to know where the problem could be. – jfriend00 Dec 10 '21 at 16:07
  • Sorry, I added the missing / (in the code it was ok). If I do the call withput params the app works as expected. I have other routes and everything works ok, excepto this one with the params. – Faabass Dec 10 '21 at 17:16
  • I found the issue, I'm currently working to fix it... The issue is that param1 is an URL, so it seems that this confuse the router.. I´m checking how to send a URL through a param – Faabass Dec 10 '21 at 17:29
  • URLs embedded in the URL as query parameters need to be encoded properly so they don't appear to be part of the path. See [How to encode URL parameters](https://stackoverflow.com/questions/8135132/how-to-encode-url-parameters). You probably want to use `encodeURIComponent()` on the URL parameter itself. – jfriend00 Dec 10 '21 at 17:34

1 Answers1

0

If you're building a URL with a URL itself as a parameter, then you need to call encodeURIComponent() on the embedded URL:

let url = "http://localhost:8080/api/v1/contr/method?url=" + encodeURIComponent(otherUrl);

This encodes the parameter in a way that will not be confused with the path of the URL during URL parsing. See doc on encodeURIComponent() for more info.

You need to use encodeURIComponent() on any parameter that contains characters that are special when it comes to URL parsing. They will then be encoded in hex such as %2F which will cause them to not match any of the URL parsing. And, the URL parsing in Express already automatically decodes them for you.

jfriend00
  • 683,504
  • 96
  • 985
  • 979