Redirect Externally After POST Request (Ruby on Rails 7)

Viewed 512

In Rails 7, I am trying to use redirect_to to redirect the browser to an external website after that browser submits a POST request.

I have a view with a form:

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

A controller:

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

And my routes:

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

I go to http://localhost:3000/articles/new, and enter the data into the form. After submitting, the page simply reloads (in other words, I am still on http://localhost:3000/articles/new). I do not get redirected to https://google.com, as I expect.

Doing the POST request in Insomnia, the redirect works without any issues.

Also, I tested what I believe would be the way to accomplish this in NodeJS (using Express), with the following code. This redirect works in both browsers without any issue.

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

From my understanding, Rails is just writing a 'Location' header, same as I am doing manually in Express. Rails does seem to write quite a few more headers than Express, however, so maybe one of those is what's causing the issue.

Any help would be much appreciated. Thank you!

0 Answers
Related