Sinatra and question mark

依然范特西╮ 提交于 2019-12-29 07:32:09

问题


I need to make some methods with Sinatra that should look like:

http//:localhost:1234/add?string_to_add

But when I declare it like this:

get "/add?:string_to_add" do
...
end

it doesn't see the string_to_add param.

How should I declare my method and use this parameter to make things work?


回答1:


In a URL, a question mark separates the path part from the query part. The query part normally consists of name/value pairs, and is often constructed by a web browser to match the data a user has entered into a form. For example a url might look like:

http://example.com/submit?name=John&age=93

Here the path section in /submit, and the query sections is name=John&age=93 which refers to the value “John” for the name key, and “93” for the age.

When you create a route in Sinatra, you only specify the path part. Sinatra then parses the query, and makes the data in it available in the params object. In this example you could do something like this:

get '/submit' do
  name = params[:name]
  age = params[:age]
  # use name and age variables
  ...
end

If you use a ? character when defining a Sinatra route, it makes part of the url optional. In the example you used (get "/add?:string_to_add"), it will actually match any url starting with /ad, then optionally another d, and then anything else will be put in the :string_to_add key of the params hash, and the query section will be parsed separately. In other words the question mark makes the preceding d character optional.

If you want to get the ‘raw’ text of the query string in Sinatra, you can use the query_string method of the request object. In your example that would look something like this:

get '/add' do
  string_to_add = request.query_string
  ...
end

Note that the route doesn’t include the ? character, just the base /add.




回答2:


You should declare it as:

get "/add?:string_to_add?" do
...
end


来源:https://stackoverflow.com/questions/15774187/sinatra-and-question-mark

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!