Rails with React app on Heroku routes don't work on refresh

狂风中的少年 提交于 2020-02-06 10:01:44

问题


I have been trying to build a Rails API with an integrated React front end and deploy it to Heroku. I am using create-react-app to build the React app in a directory called "client" within the Rails project folder. I run the Rails api on localhost:3001 and the React app on localhost:3000. And it works when I deploy it to Heroku except when I am using a React Router url and try to refresh the page, or if I try to copy and paste the URL in the browser. It's the same result on multiple browsers. For example if I go to the root url: https://appname.herokuapp.com it will display the React app with a navbar. If I click on "articles" it will take me to https://appname.herokuapp.com/articles and display the react articles page. However if I refresh the browser I just get an empty page. Same if I copy/paste this url in a browser.

I have followed three separate tutorials on deploying a Rails/React app to Heroku all from around 2018. They all mention this issue and offer the exact same solution.

In app/controllers/application_controller.rb add this action:

def fallback_index_html
  render :file => 'public/index.html'
end

And in the routes add this route at the bottom:

# config/routes.rb
get '*path', to: "application#fallback_index_html", constraints: ->(request) do
  !request.xhr? && request.format.html?
end

They all say this will work. But after trying three separate tutorials that all fail on the same issue I am at a loss. I know that on the page refresh the app is looking for the Rails routes not the React Router routes. The above solution is not working. Maybe something changed with Heroku, Rails or React that is preventing this from working now. How do I fix this?


回答1:


I don't know if you are still searching for an answer to this, but you described my situation exactly. I eventually found this post that worked for me.

It looks like ActionController::API cannot render files, but ActionController::Base can. So changing your application controller's inheritance might solve it. The solution linked above gives a suggestion for avoiding bloat too.



来源:https://stackoverflow.com/questions/56863391/rails-with-react-app-on-heroku-routes-dont-work-on-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!