How to redirect web page from a specfic page in Si

2019-09-18 17:11发布

In Sinatra, how to redirect a web page from a specific page?

require 'sinatra'

get "/A" do
    redirect '/B' 
end

get "/B" do 
    # if comes from A
    #     "IT COMES FROM A"    
    # else not from A
    #     "NOT FROM A , REDIRECT TO C"
    #     redirect '/C'
    # end
end

I want to learn how to do this?

Can I use JavaScript or HTML to do what I want to do?

Or, it must be done in Sinatra?


I tried this, but it keeps null ,

get "/B" do
    mypath = URI(request.referer || '').path
    if mypath == '/A'
      "hi i am b , u come from a"
    else
      "--#{request.referrer}--"
      redirect '/C'
  end
end

2条回答
Luminary・发光体
2楼-- · 2019-09-18 17:41

The information of the HTTP referrer can be retrieved via:

request.referrer

But if it is a redirect initiated by the server, it doesn't count as the referrer to the target page. In short terms:

If /A redirects to /B because the server told the client the page moved (status 302), the referrer is not /A but the page which linked to /A or nothing, if /A got requested directly.

To answer the question: You have to use client side redirecting in order to get your idea working. Javascript can do the trick (placed on /A):

<script type="text/javascript">window.location = '/B';</script>
查看更多
乱世女痞
3楼-- · 2019-09-18 17:56

You can check for the referrer path to do so

URI(request.referrer).path

Better approach would be to pass some parameter in the query string and you can redirect based upon its presence.

查看更多
登录 后发表回答