使用 sinatra 在块之间传递数据

发布于 2024-08-30 06:55:26 字数 247 浏览 4 评论 0原文

我正在尝试使用 sinatra 在块之间传递数据。例如:

@data = Hash.new
post "/" do
   @data[:test] = params.fetch("test").to_s
   redirect "/tmp"
end

get "/tmp" do
   puts @data[:test]
end

但是,每当我到达 tmp 块时,@data 就是 nil 并抛出错误。这是为什么?

I'm trying to pass data between blocks using sinatra. For example:

@data = Hash.new
post "/" do
   @data[:test] = params.fetch("test").to_s
   redirect "/tmp"
end

get "/tmp" do
   puts @data[:test]
end

However whenever i get to the tmp block @data is nil and throws an error. Why is that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏九 2024-09-06 06:55:26

原因是浏览器实际上执行了两个单独的 HTTP 请求。

Request: POST /
Response: 301 -> Location: /tmp
Request: GET /tmp
Response: ...

两个请求意味着两个单独的进程,因此一旦发送第一个响应,@data 实例变量就会被清除。
如果要保留信息,则需要使用cookie或session,否则在querystring中传递数据

post "/" do
   test = params[:test]
   redirect "/tmp?test=#{test}"
end

get "/tmp" do
   puts params[:test]
end

The reason is because the browser actually performs two separate HTTP requests.

Request: POST /
Response: 301 -> Location: /tmp
Request: GET /tmp
Response: ...

Two requests means two separate processes thus the @data instance variable is cleared once the first response is sent.
If you want to preserve the information, you need to use cookies or sessions, otherwise pass the data in querystring

post "/" do
   test = params[:test]
   redirect "/tmp?test=#{test}"
end

get "/tmp" do
   puts params[:test]
end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文