簡體   English   中英

POST 請求后從外部重定向(Ruby on Rails 7)

[英]Redirect Externally After POST Request (Ruby on Rails 7)

在 Rails 7 中,我試圖在瀏覽器提交 POST 請求后使用redirect_to將瀏覽器重定向到外部網站。

我有一個表單視圖:

<!-- view/articles/new.html.erb -->
<h1>New Article</h1>
<%= form_with model: @article do |form| %>
  <%= form.label :mystring %>
  <%= form.text_field :mystring %>
<% end %>

一個 controller:

class ArticlesController < ApplicationController
  def create
    # Do some active record stuff...
    redirect_to 'https://google.com', allow_other_host: true
  end
end

我的路線:

Rails.application.routes.draw do
  resources :articles
end

我go到http://localhost:3000/articles/new,把數據填入表格。 提交后,頁面只是重新加載(換句話說,我仍然在 http://localhost:3000/articles/new)。 正如我所料,我沒有被重定向到https://google.com

Insomnia中執行 POST 請求,重定向工作沒有任何問題。

此外,我使用以下代碼測試了我認為在 NodeJS(使用 Express)中實現此目的的方法。 此重定向適用於兩種瀏覽器,沒有任何問題。

app.post('/articles/create', function(req, res){
  res.writeHead(302, {
    'Location': 'https://google.com'
  });
  res.end();
});

據我了解,Rails 只是在寫一個“位置”header,就像我在 Express 中手動做的一樣。 然而,Rails 似乎確實比 Express 編寫了更多的標頭,所以可能其中之一就是導致問題的原因。

任何幫助將非常感激。 謝謝!

遇到了同樣的問題,想通了。 您需要將data: { turbo: false }添加到您的表單方法中:

<%= form_with(model: article, method: :post, data: { turbo: false }) do |form| %>

對我來說,這在本地使用 localhost:3000 而不是http://127.0.0.1:3000/並且采用這種格式

    format.html { redirect_to(root_url(subdomain: @account.subdomain), allow_other_host: true, notice: "Account was successfully updated.") }

哪里沒有

 # format.html { redirect_to root_url(subdomain: @account.subdomain), allow_other_host: true, notice: "Account was successfully updated." }

format.html { redirect_to(root_url(subdomain: @account.subdomain), allow_other_host: true, notice: "賬戶已成功更新。") }

有關這里重定向的更多信息https://api.rubyonrails.org/classes/ActionController/Redirecting.html#method-i-redirect_to

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM