LoginSignup
1

More than 5 years have passed since last update.

AWS ELasticBeanstalkのRails環境でSPAを動かすには

Last updated at Posted at 2018-05-20

TL;DR

RailsのルーティングはAPIのパス以外は、Vueのルートパスにルーティングするように設定したというだけの話。

前提

  • インスタンス
    • 環境: Puma with Ruby 2.5 running on 64bit Amazon Linux/2.7.2
    • フロント: Vue.js(Nuxt.js)
  • Rails設定
    • APIモードではなく通常のプロジェクトで作成
  • Vueの配置位置
    • app/public/{VueRoot}

経緯

ローカルで開発している段階では以下のようにRailサーバとVueサーバ別個に立ち上げていたので問題は起きなかった。というか後に問題になることを気づかなかった。

$ cd {RailsRoot}
$ rails s // endpoint -> localhost:3000
$ cd {RailsRoot}/public/{VueRoot}
$ npm run build // localhost:3001

// ブラウザでlocalhost:3001にアクセス

AWS上にデプロイ後

Railsアプリケーションとしてデプロイしてるので、当然RailsにアクセスしてVueを表示したいわけです。なのでまず、RailsルートにアクセスしたらVuの起動ページを返す設定を追加。

# routes.rb
Rails.application.routes.draw do
  root to: 'hoge#top'
  # Rails APIのルーティング設定は省略
end

# hoge_controller.rb
class HogeController < ApplicationController
  def top
    # return Vue root page
    render file: 'public/fuga/dist/index.html', layout: false, content_type: 'text/html'
  end
end

トップページは表示されました。

下層ページ

Vue側のルーティングが動いた際、Railsのルーティングが動いてRailsの404が表示されてしまう。
→おそらくVueのルーティング〜レンダリングとRailsの404、どちらが先に動くかは不定になると思われる。

なので下層ページの際はRails側のルーティングは動かないようにしたい。

# routes.rb
Rails.application.routes.draw do
  root to: 'hoge#top'
  # Rails APIのルーティング設定は省略


  # !!! 下記を追加 !!!
  get '*path', to: 'hoge#top'

end

これでとりあえずOKでした。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1