簡體   English   中英

我應該如何將 React 前端添加到使用 Rails 構建的 Web 應用程序中?

[英]How should I approach adding a react front-end to a web app built with rails?

我有一個應用程序,我在后端用 ruby​​ on rails 構建了一個應用程序,前端是簡單的 rails 視圖。 我想在前端添加反應以使其看起來更好。 我已經閱讀了有關使用 react-rails gem 或創建新的 react 應用程序並僅將 rails 應用程序用作 API 的內容,所以我想知道最好的方法是什么。 我還使用 devise ruby​​ gem 來處理用戶身份驗證——但是我看到一些事情表明如果我想使用 rails API 路線,我需要使用 devise_token_auth gem ......你會如何處理添加反應前端到一個完全構建的 Rails 應用程序?

我已經完成了你提到的兩種風格,根據我自己的經驗,我更喜歡有一個單獨的反應項目和使用 rails api 可能是因為我使用 docker 進行我的構建並且在我使用 rails-react gem 和 webpacker 時遇到了一些問題,但優點是是您不必進行 2 次部署,在這兩種方法中您都必須設置 API。

ps:webpacker 在 rails 中的預編譯有時會變得非常繁重

對於兩者,您都需要一個用於身份驗證的設計 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

可能有最好的方法來做到這一點,但對我有用,哈哈

暫無
暫無

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

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