Cannot match absolute URLs with port number
See original GitHub issueDescribe the bug
Recently in version 0.36.0
path-to-regexp
was used over node-match-path
to have similar matching behaviour as react-router
and express
. However, path-to-regexp
doesn’t seem to match absolute URLs as node-match-path
does. It feels that using path-to-regexp
is a super valuable step forward but can more easily break mocks than anticipated.
Environment
msw: 0.36.3
nodejs: 17.x.x
To Reproduce
Example 1
- Define a handler with an absolute url such as
rest.get('http://localhost:1234/*')
- Execute a request against
http://localhost:1234/foo/bar
Example 2
- Define a handler with an absolute url such as
rest.get('/:firstSegment/:secondSegment')
- Execute a request against
http://localhost:1234/foo/bar
Example 3
- Define a handler with an absolute url such as
rest.get('http\\://localhost\\:3456/:project/:application')
- Execute a request against
http://localhost:1234/foo/bar
In all examples nothing will be matched or an error will be thrown.
Expected behavior
The URL to be matched or improved documentation how to deal with absolute URLs. It seems that path-to-regexp
requires some escaping while not working with “catch-all” handers as well. Given that path-to-regexp
will continue to be used a few more practical examples for migrating handlers with full urls could help the community if I am not the only one having this issue.
Issue Analytics
- State:
- Created 2 years ago
- Reactions:1
- Comments:5 (5 by maintainers)
Top GitHub Comments
Hey, @tdeekens. Thanks for reporting this.
I still treat this as an issue on our side. The library should escape the port the same as it automatically escapes the protocol. I believe we can achieve that by changing the logic of this coercing function:
https://github.com/mswjs/msw/blob/d5b7312969ede03031d429c9fdd38a4d783710d1/src/utils/matching/matchRequestUrl.ts#L17-L46
You can see that it escapes the protocol already. We can add another regular expression to handle the port number. Would you be interested in opening a pull request with this fix?
Just learning that
msw
tries to coerce the path to apath-to-regexp
compatible version e.g. converting ahttp://localhost:3456/*"
to a"http\\://localhost:3456/(.*)
. Still unsure why my handler stopped matching.I just assumed it wouldn’t do that when debugging and ended up with double escaping.
Update: I assume cause the port is not escaped.