如何使用 Sinatra 进行发布/重定向/获取?

发布于 2024-08-30 13:00:39 字数 139 浏览 3 评论 0原文

Sinatra 相当于 Rails 的 redirect_to 方法吗?我需要遵循表单提交的 Post/Redirect/Get 流程,同时保留传递到我的视图的实例变量。使用redirect方法时实例变量会丢失。

What's Sinatra's equivalent of Rails' redirect_to method? I need to follow a Post/Redirect/Get flow for a form submission whilst preserving the instance variables that are passed to my view. The instance variables are lost when using the redirect method.

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

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

发布评论

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

评论(2

千里故人稀 2024-09-06 13:00:40

Sinatra 中的重定向是最简单易用的。

所以下面的代码可以解释:

require 'rubygems'
require 'sinatra'

get '/' do
  redirect "http://example.com"
end

您也可以像这样重定向到当前应用程序中的另一个路径,尽管此示例将删除一个方法。

delete '/delete_post' do
  redirect '/list_posts'
end

使用此重定向指令的一个非常常见的地方是在“身份验证”下,

def authorize!
  redirect '/login' unless authorized?
end

您可以在以下位置查看更多示例:

Sinatra 手册

常见问题解答

扩展

至于你的第二个问题,将变量传递到视图中,可能是这样的:

get '/pizza/:id' do
  # makeing lots of pizza
  @foo = Foo.find(params[:id])
  erb '%h1= @foo.name'
end

Redirect in Sinatra is the most simple to use.

So the code below can explain:

require 'rubygems'
require 'sinatra'

get '/' do
  redirect "http://example.com"
end

You can also redirect to another path in your current application like this, though this sample will delete a method.

delete '/delete_post' do
  redirect '/list_posts'
end

A very common place where this redirect instruction is used is under Authentication

def authorize!
  redirect '/login' unless authorized?
end

You can see more samples under:

Sinatra Manual

FAQ

Extensions

As for your second question, passing variables into views, it's possible like this:

get '/pizza/:id' do
  # makeing lots of pizza
  @foo = Foo.find(params[:id])
  erb '%h1= @foo.name'
end
扛刀软妹 2024-09-06 13:00:40

Sinatra Book 应该可以解答您的问题。特别是“重定向”部分。

引自书中:

重定向实际上会向浏览器发送回 Location 标头,然后浏览器会向指示的位置发出后续请求。由于浏览器发出后续请求,因此您可以重定向到应用程序中的任何页面或完全另一个站点。

重定向期间的请求流程为:浏览器 –>服务器(重定向到“/”)–>浏览器(请求'/')–>服务器(“/”的结果)

The Sinatra Book should clear your question. Especially the "Redirect" part.

Quoted from the book:

The redirect actually sends back a Location header to the browser, and the browser makes a followup request to the location indicated. Since the browser makes that followup request, you can redirect to any page, in your application, or another site entirely.

The flow of requests during a redirect is: Browser –> Server (redirect to ’/’) –> Browser (request ’/’) –> Server (result for ’/’)

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