简体   繁体   English

如何在Rails json API体系结构中呈现javascript前端应用程序?

[英]How to render the javascript frontend application, in rails json API architecture?

I am working on a Rails app, with front end on martyjs/reactjs. 我正在使用Rails应用程序,前端在martyjs / reactjs上。 I've set a route that matches every pattern, so the user can follow any link deep in my reactjs app. 我设置了一个匹配每种模式的路由,因此用户可以在我的reactjs应用程序中深入任何链接。 I am implementing login/logout and I've came up with a problem. 我正在执行登录/注销,但遇到了问题。 In my application_controller.rb I've set up a filter: In my application_controller.rb我设置了一个过滤器:

  before_action :authenticated_account?
  def authenticated_account?
        customer = User::Customer.find_by_session_token cookies.signed[:session_token]
        if customer.verify_session!(cookies.signed[:session_token],request.remote_ip ) then else resp = Response.new("Not authorized", nil, 401) end
         return respond resp if resp
      end

But rightly, this deny my interface to render, since the server receive a JSON with the message. 但是正确的是,由于服务器收到带有消息的JSON,因此这拒绝了我的界面呈现。 This is a good response when my app it is already loaded, because my app intercept gracefully the 401 code. 当我的应用程序已经加载时,这是一个很好的响应,因为我的应用程序可以正常拦截401代码。

But I am not find out a soluton for rendering my js app and respond to the code if a user open a window and go to a link directly deep in my reactjs app. 但是我没有找到解决方案来渲染我的js应用程序,如果用户打开一个窗口并直接进入我的reactjs应用程序深处的链接,则无法响应代码。

Like I've said, I knew that I was missing something. 就像我说过的,我知道我缺少一些东西。 I've simply dedicated a controller action to the render of the html page with the onePageApplication, and skipped the authentication check on that. 我只是使用onePageApplication将控制器动作专用于html页面的呈现,并跳过了对此的身份验证检查。

So, recap: 因此,回顾一下:

To serve a onePageApp with rails. 使用rails服务onePageApp。

set the route for your api calls: 为您的api调用设置路由:

namespace :api do
    ...
  end

and the route for serving the UI: 以及提供UI的路线:

scope "/", :format => false do

    get "/" => "application#uiserve"
    get "/*path" => "application#uiserve"

    root :to => "application#index"

  end

In this way, when a user digit a deep link in my app, it will always be matched, and served with the HTML page with the JS code. 这样,当用户在我的应用程序中输入深层链接时,它将始终被匹配,并与带有JS代码的HTML页面一起使用。

The requests that the app will make, will be under the namespace :api so it will be routed correctly 应用程序发出的请求将在名称空间:api下,因此可以正确路由

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM