我实施了一条简单的路线:
get '/test' do
params
end
当我在没有编码参数的情况下调用它时,如
/test?plip=plop
=> ["plip", "plop"]
我可以毫无问题地检索我的参数。
但是,使用编码参数:
/test?plip%3Dplop
=> ["plip=plop", nil]
键/值不再匹配。 我们有解决这个问题的方法吗?
提前谢谢。
答案 0 :(得分:1)
由于查询值可以编码(并且如果它们包含影响解析的字符,那么应该没有应用程序收到=
作为%3D
的时间是查询字符串的一部分,而不仅仅是查询值。 Rack为您处理查询字符串的解析,因此您需要担心的是,在您的示例中,params["plip"]
的值是否需要解码,但我不知道我认为您甚至不必担心这一点,如下例所示:
require 'sinatra'
get '/' do
params.inspect
end
我通过IRB获得了CGI编码的字符串:
URI.encode "https://stackoverflow.com/questions/28987085/how-to-decode-route-parameters-in-sinatra"
=> "https://stackoverflow.com/questions/28987085/how-to-decode-route-parameters-in-sinatra"
然后我运行应用程序并检查输出(注意,我的终端的curl
调用中有一些额外的转义字符,当curl
运行时它们被删除所以忽略那些) :
$ curl http://localhost:4567/
127.0.0.1 - - [14/Mar/2015:12:10:03 +0900] "GET / HTTP/1.1" 200 2 0.0045
localhost - - [14/Mar/2015:12:10:03 JST] "GET / HTTP/1.1" 200 2
- -> /
{}%
$ curl http://localhost:4567/\?plip\=plop
127.0.0.1 - - [14/Mar/2015:12:10:25 +0900] "GET /?plip=plop HTTP/1.1" 200 16 0.0005
localhost - - [14/Mar/2015:12:10:25 JST] "GET /?plip=plop HTTP/1.1" 200 16
- -> /?plip=plop
$ curl http://localhost:4567/\?plip\=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F28987085%2Fhow-to-decode-route-parameters-in-sinatra
127.0.0.1 - - [14/Mar/2015:12:11:51 +0900] "GET /?plip=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F28987085%2Fhow-to-decode-route-parameters-in-sinatra HTTP/1.1" 200 98 0.0005
localhost - - [14/Mar/2015:12:11:51 JST] "GET /?plip=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F28987085%2Fhow-to-decode-route-parameters-in-sinatra HTTP/1.1" 200 98
- -> /?plip=https%3A%2F%2Fstackoverflow.com%2Fquestions%2F28987085%2Fhow-to-decode-route-parameters-in-sinatra
{"plip"=>"https://stackoverflow.com/questions/28987085/how-to-decode-route-parameters-in-sinatra"}%
从最终输出中可以看出,传入参数已经为您解码:
{"plip"=>"https://stackoverflow.com/questions/28987085/how-to-decode-route-parameters-in-sinatra"}%