简单的Sinatra会话不起作用

时间:2014-12-19 15:56:32

标签: sinatra rack thin

根据the Sinatra FAQ,像这样的Sinatra应用应该有效:

enable :sessions

class MyApp < Sinatra::Base
  get '/foo' do
    session[:message] = 'Hello World!'
    redirect to('/bar')
  end

  get '/bar' do
$stderr.puts session[:message]
    session[:message]   # => 'Hello World!'
  end
end

给出config.ru之类的:

require 'sinatra'

require './test.rb' # which contains the above MyApp

run MyApp

并通过以下方式调用它:

thin -R config.ru -p 4567 start

当Sinatra代码运行时,它没有设置cookie。您可以在 curl -vL http://localhost:4567/foo 输出中看到这一点:

* Hostname was NOT found in DNS cache
*   Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 4567 (#0)
> GET /foo HTTP/1.1
> User-Agent: curl/7.35.0
> Host: localhost:4567
> Accept: */*
> 
< HTTP/1.1 302 Moved Temporarily
< Content-Type: text/html;charset=utf-8
< Location: http://localhost:4567/bar
< Content-Length: 0
< X-XSS-Protection: 1; mode=block
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< Connection: keep-alive
* Server thin is not blacklisted
< Server: thin
< 
* Connection #0 to host localhost left intact
* Issue another request to this URL: 'http://localhost:4567/bar'
* Found bundle for host localhost: 0x1180760
* Re-using existing connection! (#0) with host localhost
* Connected to localhost (127.0.0.1) port 4567 (#0)
> GET /bar HTTP/1.1
> User-Agent: curl/7.35.0
> Host: localhost:4567
> Accept: */*
> 
< HTTP/1.1 200 OK
< Content-Type: text/html;charset=utf-8
< Content-Length: 0
< X-XSS-Protection: 1; mode=block
< X-Content-Type-Options: nosniff
< X-Frame-Options: SAMEORIGIN
< Connection: keep-alive
* Server thin is not blacklisted
< Server: thin
< 
* Connection #0 to host localhost left intact

另外,$stderr.puts session[:message]不会发出消息,而只是一个空行。

切换enable :sessions以下内容也没有影响:

use Rack::Session::Cookie, :key => 'rack.session',
                       :domain => 'foo.com',
                       :path => '/',
                       :expire_after => 2592000, # In seconds
                       :secret => 'change_me'

这是thin 1.6.3,rack 1.6.0和sinatra 1.4.5。

我哪里错了?除了现在睡眠不足之外......

谢谢!

1 个答案:

答案 0 :(得分:2)

您需要在应用类中移动enable :sessions行:

class MyApp < Sinatra::Base
  enable :sessions
  #...

现在,您可以使用该行启用Sinatra::Application应用的会话,该应用是在您使用“classic” style时运行的应用,但不会在此处运行。您需要在应用中启用会话。

通过该更改,您应该会看到Cookie标头已设置,但您需要使用curl -vL -b cookie_file -c cookie_file http://localhost:4567/foo之类的内容来查看它实际上与curl一起使用(以便存储和重新发送Cookie)。