【问题标题】:Rails API - POST activationRails API - POST 激活
【发布时间】:2017-10-03 15:44:29
【问题描述】:

我正在尝试在 Rails API 应用程序中实现用户帐户。 我有用于注册和登录的用户逻辑,但我的问题是电子邮件链接是 GET 请求,而所需的操作是 POST。我可以像这样在 Postman 中通过 POST 请求手动激活 URL:

http://localhost:3000/users/confirm-request?token=b96be863aced91480a2a

如何通过单击电子邮件中的链接来完成此操作?

我的用户控制器:

    class UsersController < ApplicationController

  def create
    user = User.new(user_params)
    if user.save
      UserMailer.registration_confirmation(user).deliver
      render json: { status: 201 }, status: :created
    else
      render json: { errors: user.errors.full_messages }, status: :bad_request
    end
  end

  def confirm
    token = params[:token].to_s
    user = User.find_by(confirmation_token: token)

    if user.present? && user.confirmation_token_valid?
      user.mark_as_confirmed!
      render json: {status: 'User confirmed successfully'}, status: :ok
    else
      render json: {status: 'Invalid token'}, status: :not_found
    end
  end

  def login
    user = User.find_by(email: params[:email].to_s.downcase)

    if user && user.authenticate(params[:password])
      if user.confirmed_at?
        auth_token = JsonWebToken.encode({user_id: user.id})
        render json: {auth_token: auth_token}, status: :ok
      else
        render json: {error: 'Email not verified' }, status: :unauthorized
      end
    else
      render json: {error: 'Invalid username / password'}, status: :unauthorized
    end
  end

  private

  def user_params
    params.require(:user).permit(:name, :email, :password, :password_confirmation)
  end

end

我的路线.rb:

Rails.application.routes.draw do
  resources :users, only: :create do
    collection do
      post 'confirm'
      post 'login'
    end
  end

registration_confirmation.text.erb:

Hi <%= @user.name %>,

Thanks for registering. To confirm your registration click the URL below.

<%= confirm_users_url(@user.confirmation_token) %>

【问题讨论】:

  • AFAIK(据我所知),您不能将链接添加到 POST,因为默认情况下所有链接都是 GET。现在,您可以在 POST 中创建链接,但这已经通过 JS 完成。话虽如此,电子邮件并不真正支持 JS(也许是一些?),因此最好只使用 GET 请求。要回答您的问题:您只需将您的 routes.rb 从 post 'confirm' 更改为 get 'confirm'

标签: ruby-on-rails


【解决方案1】:

更改registration_confirmation.text.erb的代码

Hi <%= @user.name %>,

Thanks for registering. To confirm your registration click the URL below.

<%#= confirm_users_url(token: @user.confirmation_token) %>
<a href="/users/confirm?token=<%=@user.confirmation_token%>"></a>

Routes.rb

Rails.application.routes.draw do
  resources :users, only: :create do
    collection do
      get 'confirm'
      post 'login'
    end
  end
end

【讨论】:

  • 对不起,我的实验结果弄错了。
  • (如果我不清楚)修复此问题并不能解决问题。
  • 不,我在浏览器中使用链接时遇到的错误是:ActionController::RoutingError: No route matches [GET] "/users/confirm"
  • 我不敢相信它这么简单,我很确定我尝试将路线从 post 更改为 get before。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-21
  • 1970-01-01
  • 2017-01-31
  • 2018-01-22
  • 1970-01-01
相关资源
最近更新 更多