【问题标题】:Simple Sinatra Sessions Not Working简单的 Sinatra 会话不起作用
【发布时间】:2014-12-19 15:56:31
【问题描述】:

根据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。

我哪里错了?除了现在可悲的睡眠不足......

谢谢!

【问题讨论】:

    标签: sinatra rack thin


    【解决方案1】:

    您需要在您的应用程序类中移动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)。

    【讨论】:

    • 实际上,仅仅看到 cookie 标头流动就是一个巨大的改进。非常感谢!
    猜你喜欢
    • 2014-05-05
    • 2016-02-26
    • 2011-01-07
    • 1970-01-01
    • 2018-10-30
    • 2014-09-11
    • 1970-01-01
    相关资源
    最近更新 更多