Rails Devise вызывает POST вместо PUT при сбросе пароля

Я использую devise для аутентификации и у меня проблема в форме восстановления пароля, ссылка на которую отправлена ​​по электронной почте. Когда я определяю новый пароль, форма отправляет запрос POST вместо PUT. Он перенаправляет пользователя/пароль # с уведомлением «Электронная почта не может быть пустой».

Итак, в edit.html.erb есть метод: :put, но он не работает. <%= form_for(resource, as: resource_name, url: user_password_path(resource_name), html: { method: :put }) do |f| %>

Я застрял в этом весь день и не нашел выхода

Это полный файл edit.html.erb

<h2>Change your password</h2>

<%= form_for(resource, as: resource_name, url: user_password_path(resource_name),  method: :PUT) do |f| %>
  <%= render "devise/shared/error_messages", resource: resource %>
  <%= f.hidden_field :reset_password_token %>

  <div class="field">
    <%= f.label :password, "New password" %><br />
    <% if @minimum_password_length %>
      <em>(<%= @minimum_password_length %> characters minimum)</em><br />
    <% end %>
    <%= f.password_field :password, autofocus: true, autocomplete: "new-password" %>
  </div>

  <div class="field">
    <%= f.label :password_confirmation, "Confirm new password" %><br />
    <%= f.password_field :password_confirmation, autocomplete: "new-password" %>
  </div>

  <div class="actions">
    <%= f.submit "Change my password" %>
  </div>
<% end %>

Это сгенерированная форма

<h2>Change your password</h2>

<form class="new_user" id="new_user" action="/user/password.user" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="_method" value="patch" /><input type="hidden" name="authenticity_token" value="Zf5rxkU11tVmt4i8hDpFPDL5y+/jzRQT/O/si6RnraidCN5vxofmVS1abO4nJ8iqlncZfCRr1jdLjMfxwMx45A==" />

  <input type="hidden" value="xk6EkLsyxCyvvpDyY6Ug" name="user[reset_password_token]" id="user_reset_password_token" />

  <div class="field">
    <label for="user_password">New password</label><br />
      <em>(6 characters minimum)</em><br />
    <input autofocus="autofocus" autocomplete="new-password" type="password" name="user[password]" id="user_password" />
  </div>

  <div class="field">
    <label for="user_password_confirmation">Confirm new password</label><br />
    <input autocomplete="new-password" type="password" name="user[password_confirmation]" id="user_password_confirmation" />
  </div>

  <div class="actions">
    <input type="submit" name="commit" value="Change my password" data-disable-with="Change my password" />
  </div>
</form>

Мой контроллер паролей

# frozen_string_literal: true

# Deals with user login and generates JWT
class User::PasswordsController < Devise::PasswordsController
  prepend_before_action :require_no_authentication
  # Render the #edit only if coming from a reset password email link
  append_before_action :assert_reset_token_passed, only: :edit
  skip_before_action :verify_authenticity_token

  respond_to :json
  wrap_parameters :user

  before_action :configure_permitted_parameters, if: :devise_controller?




  def create
   super
  end

  def edit 
    super
  end

  def update 
    super
  end

  def new 
    super
  end

end

Мои маршруты.рб

constraints subdomain: 'api' do
    scope module: 'user' do
      devise_for  :users,
                  path: '/user',
                  path_names: {
                    registration: 'signup',
                    sign_in: 'login',
                    sign_out: 'logout'
                  },
                  controllers: {
                    sessions: 'user/sessions',
                    registrations: 'user/registrations',
                    passwords: 'user/passwords'
                  }

Журнал сервера

введите здесь описание изображения Заранее спасибо


person Rafael Zerbini    schedule 27.06.2019    source источник
comment
Если вы просматриваете элемент формы, говорит ли он, что method=put?   -  person ThorTL67    schedule 28.06.2019
comment
<form class="new_user" id="new_user" action="/user/password.user" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="&#x2713;" /><input type="hidden" name="_method" value="put" /><input type="hidden" name="authenticity_token" value="blabla" /> вот так.   -  person Rafael Zerbini    schedule 01.07.2019
comment
Какую версию Rails вы используете? Правильно ли вы установили rails-ujs? Это библиотека, которая делает возможным запрос PUT в HTML-формах. github.com/rails/rails-ujs   -  person tegon    schedule 01.08.2019


Ответы (1)


Я столкнулся с этой же проблемой, используя функцию сброса пароля Devise. Я добавлял Devise в приложение API Rails (config.api_only = true), и, по-видимому, промежуточное ПО Rack::MethodOverride, которое отвечает за идентификацию атрибута скрытого метода и изменение запроса на запрос PUT/PATCH, не было включено в стек промежуточного ПО только для API. В результате запрос дошел до основного приложения как POST-запрос.

Я добавил следующую строку в config/application.rb, что решило проблему:

config.middleware.insert_after Rack::Runtime, Rack::MethodOverride
person Jason L    schedule 24.05.2020