1

我有一个应用程序,我在后端使用 ruby​​ on rails 构建,前端是简单的 rails 视图。我想在前端添加反应以使其看起来更好。我已经阅读了关于使用 react-rails gem,或者创建一个新的 react 应用程序并将 rails 应用程序用作 API 的信息,所以我想知道最好的方法是什么。我还使用了 devise ruby​​ gem 来处理用户身份验证——但是我已经看到了一些建议,如果我想使用 rails API 路线,我需要使用 devise_token_auth gem ...你将如何添加一个反应前端到一个完整的 Rails 应用程序?

4

1 回答 1

1

我已经完成了您提到的两种样式,根据我自己的经验,我更喜欢拥有一个单独的反应项目并使用 rails api,这可能是因为我使用 docker 进行构建,并且在使用 rails-react gem 和 webpacker 时遇到了一些问题,但优势是您不必进行 2 次部署,在这两种方法中您都必须设置 API。

ps:rails 中的 webpacker 预编译有时会变得非常繁重

对于这两者,您都需要一个设计 JWT 令牌来进行身份验证,这里有一个关于如何设置它的好教程

如果您想同时拥有两种身份验证方法(html 和 json),您可以在会话控制器中使用类似的东西

    class Users::SessionsController < Devise::SessionsController
  respond_to :json, :html
  # before_action :configure_sign_in_params, only: [:create]

  def create
    if request.format.html?
      super
      # super {
      #   cookies[:token] = current_token || ""
      # }
    else
      resource = User.find_for_database_authentication(email: params[:email])
      return invalid_login_attempt unless resource

      if resource.valid_password?(params[:password])
        sign_in(resource, store: false)
        @payload = [resource, current_token]
        render(status: 200, success: true, json: @payload)
      else
        invalid_login_attempt
      end
    end
  end

  def invalid_login_attempt
    warden.custom_failure!
    render json: {
      success: false,
      message: 'Error with your email or password'
    }, status: 401, status: :unauthorized
  end

  def current_token
    request.env['warden-jwt_auth.token']
  end

  private

  def respond_with(resource, _opts = {})
    if request.format.html?
      super
    else
      render status: 401, success: false, json: { error: 'No autorizado' }
    end
  end

  def respond_to_on_destroy
    if request.format.html?
      super
    else
      head :ok
    end
  end
end

可能有一个最好的方法来做到这一点,但对我有用,哈哈

于 2020-02-28T14:59:08.903 回答