【问题标题】:How does the CGI cookie work in Ruby?CGI cookie 在 Ruby 中是如何工作的?
【发布时间】:2009-04-12 13:19:46
【问题描述】:

这是我一直在网上看到的关于如何设置 cookie 的示例。

require "cgi"
cookie = CGI::Cookie.new("rubyweb", "CustID=123", "Part=ABC");
cgi = CGI.new("html3")
cgi.out( "cookie" => [cookie] ){
  cgi.html{
    "\nHTML content here"
  }
}

我尝试过这样做,它设置了 cookie,然后出现了一个空白页面。

#!/usr/local/bin/ruby

require 'cgi'
load 'inc_game.cgi'
cgi = CGI.new

cookie = CGI::Cookie.new("rubyweb", "CustID=123", "Part=ABC");
cgi.out( "cookie" => [cookie] ){""}     

#see if game submit buttons pressed
doIt = cgi['play']
puts "Content-type: text/html\n\n"  

play = Game.new

#welcome
if doIt == ''
puts play.displayGreeting
end

#choose weapon
play.playGame

if doIt == 'Play'
    move = cgi['weapon']
    human = play.humanMove(move)
    computer = play.ComputerMove
    print human
    print computer
    result = play.results(human,computer)
    play.displayResults(result)
end

所以我的问题首先是,我错过了什么/做错了什么?其次,我想知道是否有人想解释 .out 与 .header 相比有什么作用,或者是否有区别?

谢谢,

李维斯

【问题讨论】:

  • 通过阅读更多内容,我发现 cgi.out 可以处理 cgi.header 的大部分内容。那么它只是一种更简洁的控制输出的方式吗?

标签: ruby cookies cgi


【解决方案1】:

我相信这条线:

cgi.out( "cookie" => [cookie] ){""}

正在刷新您的标题。

在我的 TTY 中运行代码后,

内容类型:文本/html 内容长度:0 设置 Cookie:rubyweb=CustID%3D123&Part%3DABC;路径= 内容类型:文本/html

已发出,并且“Content-Length: 0”(由 out{} 中的空字符串生成)可能告诉浏览器您已完成。

cookie = CGI::Cookie.new("rubyweb", "CustID=123", "Part=ABC");
cgi.header( "cookie" => [cookie] ,  type => 'text/html' )

#normal printing here 

最好用于发送标头。

选择“进行处理”-“然后考虑输出”模型可能会有所帮助。

require 'cgi'
load 'inc_game.cgi'

cgi = CGI.new
cookie = CGI::Cookie.new("rubyweb", "CustID=123", "Part=ABC");

output = ""; 

#see if game submit buttons pressed
doIt = cgi['play']

play = Game.new

#welcome
if doIt == ''
  output << play.displayGreeting
end

#choose weapon
play.playGame

if doIt == 'Play'
    move = cgi['weapon']
    human = play.humanMove(move)
    computer = play.ComputerMove
    output << human
    output << computer
    result = play.results(human,computer)
    output << play.displayResults(result)
end



cgi.out( "cookie" => [cookie] , type=>"text/html" ){ 
  output; 
}

【讨论】:

  • 发送标头导致内部服务器错误,但这是最适合我的选项。最后发送输出也会导致内部服务器错误,很可能是因为我在正文中打印文本并且打印内容直到最后才设置
  • 至少在那时将其视为设计错误。将打印语句深入随机代码中(通常)确实不是一个好主意
  • 好的,我会记住的。您是否知道为什么标头会在您的第一个建议中引发内部服务器错误?我在打印之前发送它。
  • 这取决于您的服务器,您需要检查您的特定服务器内部错误日志并查看它对 ISE 的解释,这可能是几十个原因之一,一个是提前终止因为无效代码。
猜你喜欢
  • 2023-04-07
  • 2013-01-03
  • 2015-08-05
  • 2011-02-17
  • 2012-12-18
  • 2012-10-13
  • 1970-01-01
  • 2011-09-28
  • 1970-01-01
相关资源
最近更新 更多