javascript - React Router doesn't encode ampersands but encodes spaces in path params - Stack Overflow

admin2025-04-19  0

I'm having an issue with react router encoding spaces but not ampersands. So localhost:8080/you & me is encoded to be localhost:8080/you%20&%20me instead of localhost:8080/you%20%26%20me and I'm using a wonky hack to decode then re-encode everything. I was wondering if anyone can remend a better solution.

I'm having an issue with react router encoding spaces but not ampersands. So localhost:8080/you & me is encoded to be localhost:8080/you%20&%20me instead of localhost:8080/you%20%26%20me and I'm using a wonky hack to decode then re-encode everything. I was wondering if anyone can remend a better solution.

Share edited Jul 9, 2019 at 20:00 reactor asked Jul 9, 2019 at 19:46 reactorreactor 1,9513 gold badges17 silver badges46 bronze badges 4
  • 4 I'd use slugs (you-me) instead, but not sure if it's possible for you. – Emile Bergeron Commented Jul 9, 2019 at 19:58
  • 2 You could use the slug nom module to do this for you if you need this as a path parameter. However, I think it's a route URL and not a path parameter. – technogeek1995 Commented Jul 9, 2019 at 20:09
  • 3 agree with @EmileBergeron you shouldn't be using special characters in the URL. Lets say you are loading a list of elements that is paginated. You would request like this some.api/my/get/route?page=2&rows=20 The ? and = and & are reserved for url parameters. You should rethink how to define your routes where you dont need special characters (non alphanumeric). – John Ruddell Commented Jul 9, 2019 at 20:24
  • Amen. Too many people today don't even care which characters need to be escaped, they just hand-wave it away and just do naive string parisons in the router. The React history push function is oblivious about the rules and escaping and normalization of URLs. I have seen cases where I "fixed" the URL to be properly encoded, and it broke the router - I had to make it wrong to make it work. – doug65536 Commented Mar 25 at 20:36
Add a ment  | 

1 Answer 1

Reset to default 6

Do not use non-alphanumeric characters in the URL. Some characters like &, /, ?, and = have special meanings in URLs. Even though react-router does not throw an error when you create a route ponent with a & in the url, as you have noticed, you'll end up with wonky behavior. It's best practice to avoid strange edge cases. You can read more about allowed characters in a url here.

As a workaround, you can achieve nearly the same URL with localhost:8080/you-and-me. This is a safe url without spaces and special characters. It's also human readable, which anything with spaces wouldn't be easily readable as it would be encoded.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1745058026a282521.html

最新回复(0)