且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用路由和查询字符串参数是否错误?

更新时间:2023-11-19 21:11:34

如果要实现搜索功能或其他需要使用的功能具有多个可选参数,***使用查询字符串参数。您可以提供全部,某些或不提供任何商品,并将它们按任何顺序放置,这样就可以使用。

If you are implementing a search feature, or other type of feature where you need to have multiple optional parameters, it is better to use query string parameters. You can supply all of them, some of them, or none of them and put them in any order, and it will just work.

// Anything Goes
/controller/action?a=123&b=456&c=789
/controller/action?c=789&a=123&b=456
/controller/action?b=456&c=789
/controller/action?c=789
/controller/action

另一方面,如果您使用URL路径和路由,则只有在其右侧没有其他参数时,该参数才是可选的。

On the other hand, if you use URL paths and routing, a parameter can only be optional if there is not another parameter to the right of it.

// OK
/controller/action/123/456/789
/controller/action/123/456
/controller/action/123

// Not OK
/controller/action/123/456/789
/controller/action/456/789
/controller/action/789

可以通过自定义路由,使其能够以任何顺序传递可选值,但是当查询字符串不存在时,似乎还有很长的路要走

It is possible by customizing routing to be able to pass optional values in any order, but it seems like a long way to go when query strings are a natural fit for this scenario.

要考虑的另一个因素是,放入URL的值是否具有中使用using-unsafe-characters-in-urls / rel = nofollow noreferrer>不安全字符。 URL的 path 格式不佳,有时甚至不可行,但是可以放到查询字符串中的编码字符类型的规则更加宽松。由于网址不允许使用空格,因此更适合将多字文字搜索字段与查询字符串中的空格一起编码(按原样保留),而不是尝试寻找一种解决方案,以将空格替换为-放入查询字符串,然后在运行查询时必须将其更改回服务器端的空间。

Another factor to consider is whether the values being put into the URL have unsafe characters in them that need to be encoded. It is poor form and sometimes not feasible to encode the path of the URL, but the rules of what types of encoded characters that can be put into a query string are more relaxed. Since URLs don't allow spaces, it is a better fit for a multiple word text search field to be encoded with the space in the query string (preserving it as is) rather than trying to find a solution to swapping out the space with a - to put into the query string and then having to change it back to a space on the server side when running the query.

search = "foo bar"

// Spaces OK
/controller/action?search=foo%20bar  (works fine and server is able to interpret)

// Spaces Not OK
/controller/action/foo bar/    (not possible)
/controller/action/foo%20bar/  (may work, but a questionable design choice)
/controller/action/foo-bar/    (may work, but requires conversion on the server)

最后,另一个值得考虑的选择是使用POST而不是GET,因为这意味着这些值根本不需要放在URL中。

Finally, another choice worth considering is using POST instead of GET, as that would mean these values wouldn't need to be in the URL at all.