Rails + Nuxt 環境構築 (API通信まで)

Rails + Nuxt 環境構築 (API通信まで)

フロントエンド をVue.jsのフレームワークのNuxt.jsを使用し、バックエンドをRuby on Railsの環境構築の手順を説明します。

今回の記事ではNuxtとRailsの環境構築とaxios通信をして「Hello Rails」を出力するところまでを実装します。

環境
$ rails -v
Rails 6.1.1

$ yarn -v
1.22.5

ディレクトリの作成

// 新規ディレクトリの作成
$ mkdir todo-list

// todo-listのディレクトリへ移動
$ cd todo-list

環境構築(Rails)

// RailsのAPIモードでapiという名前でプロジェクト作成 DBはpostgresを指定
todo-list $ rails new api --database=postgresql --skip-bundle --api

// apiディレクトリへ移動
$ cd api

api $ bundle install

database.ymlを編集します。

default: &default
  adapter: postgresql
  encoding: unicode
  username: <%= ENV['PG_USERNAME'] %>  # 編集
  password: <%= ENV['PG_PASSWORD'] %>  # 編集
  # For details on connection pooling, see Rails configuration guide
  # https://guides.rubyonrails.org/configuring.html#database-pooling
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

PG_USERNAMEとPG_PASSWORDはzshrcに記載のpostgresのusernameとpasswordになります。

僕の場合だと下記のように記述しています。

$ vim ~/.zshrc
export PG_USERNAME='XXXXXXXX' 
export PG_PASSWORD='YYYYYYYY'

database.ymlの編集が完了したらデータベースを作成します。

api $ bundle exec rails db:create
Created database 'api_development'
Created database 'api_test'

api $ rails s

http://localhost:3000/ にアクセスして下記の画像のように表示されたらrails側の構築は完了になります。

環境構築(Nuxt)

続いてnuxt.jsの環境構築を行っていきます。

// frontという名前でnuxtプロジェクトの作成
todo-list $ yarn create nuxt-app front

? Project name: front
? Programming language: JavaScript
? Package manager: Yarn
? UI framework: Vuetify.js
? Nuxt.js modules: (Press <space> to select, <a> to toggle all, <i> to invert selection)
? Linting tools: (Press <space> to select, <a> to toggle all, <i> to invert selection)
? Testing framework: None
? Rendering mode: Single Page App
? Deployment target: Server (Node.js hosting)
? Development tools: (Press <space> to select, <a> to toggle all, <i> to invert selection)
? What is your GitHub username? YOUR GITHUB USERNAME
? Version control system: Git

  To build & start for production:

	cd front
	yarn build
	yarn start

✨  Done in 271.27s.

nuxtのデフォルトのportは3000でrails側とバッテイングしてしまうのでportを修正します。

front/nuxt.config.js

export default {
  // 追加
  server: {
    port: 8080
  },

  // Disable server-side rendering: https://go.nuxtjs.dev/ssr-mode
  ssr: false,
  ...
}
todo-list $ cd front
front $ yarn dev

http://localhost:8080/ にアクセスして下記の画像のように表示されたらnuxt側の構築は完了になります。

axios通信(Nuxt)

環境構築が完了したのでここからAPI通信の準備をしていきます。

使用するモジュール

@nuxtjs/axios: https://github.com/nuxt-community/axios-module

@nuxtjs/proxy: https://github.com/nuxt-community/proxy-module

モジュールのインストール
front $ yarn add @nuxtjs/axios
front $ yarn add @nuxtjs/proxy

インストールが完了したらnuxt.config.js編集します。

修正内容

  1. modulesに@nuxtjs/axiosと@nuxtjs/proxyを追加する
  2. proxyのtargetにバックエンドのURLを指定する
nuxt.config.js
// 省略

  // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
  buildModules: [
    // https://go.nuxtjs.dev/vuetify
    '@nuxtjs/vuetify',
  ],

  // Modules: https://go.nuxtjs.dev/config-modules
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy',
  ],

  proxy: {
    '/api': {
      target: 'http://localhost:3000/'
    }
  },
// 省略

次にpagesの修正をしていきます。

front/pages/index.vue

<template>
  <v-row justify="center" align="center">
    <v-col cols="12" sm="8" md="6">
      <div class="text-center">
        <logo />
        <vuetify-logo />
        <v-btn @click="getApi()">GET API</v-btn>
        <div>{{ message }}</div>
      </div>
..省略

<script>
import Logo from '~/components/Logo.vue'
import VuetifyLogo from '~/components/VuetifyLogo.vue'

export default {
  components: {
    Logo,
    VuetifyLogo
  },
  data: () => {
    return {
      message: ''
    }
  },
  methods: {
    getApi() {
      const url = "/api/v1/hello"
      this.$axios.get(url)
        .then((res) => {
          this.message = res.data
        })
        .catch((error) => {
          console.log(error)
        })
    }
  }
}
</script>

上記画像のように表示されます。

<v-btn @click="getApi()">GET API</v-btn>

クリックイベントでgetApi()メソッドを実行します。

getApiのメソッドを確認します。

    getApi() {
      const url = "/api/v1/hello"
      this.$axios.get(url)
        .then((res) => {
          this.message = res.data
        })
        .catch((error) => {
          console.log(error)
        })
    }

this.$axios.get(url)はurlのGETリクエストを送信します。

/api/**の記述でproxyのtargetのurlが設定されるので

今回であれば http://localhost:3000/api/v1/hello のurlのGETリクエストということになります。

次はRails側でAPIを作成します。

axios通信(Rails)

  • ルーティングの生成
  • コントローラの作成

上記手順に沿って実装していきます。

  • ルーティングの生成
api/config/routes.rb

Rails.application.routes.draw do
  namespace :api do
    namespace :v1 do
      resources :hello, only: [:index]
    end
  end
end
$ rails routes
Prefix                       Verb   URI Pattern                 Controller#Action
api_v1_hello_index    GET    /api/v1/hello(.:format)  api/v1/hello#index

ルーティングが生成できました。次にコントローラを作成します。

api/controllers/api/v1/posts_controller.rb

module Api
  module V1
    class HelloController < ApplicationController
      def index
        render json: 'Hello Rails'
      end
    end
  end
end

これで /api/v1/helloのGETリクエスト が送られてくると `Hello Rails`のメッセージを返すAPIが完成しました。

アプリの方で「GET API」ボタンをクリックすると「Hello Rails」の文字が表示されると思います。

とりあえずAPI通信の基盤は完成しました。

しかしこのままだとどのサイトからでも http://localhost:3000/api/v1/hello のGETリクエストを受け付けることができてしまうのでCORSの設定をします。

CORSの設定をすることでフロント側のURLからしかリクエストを受け付けないように設定できます。

cors設定(Rails)

api/Gemfile

## 省略
gem 'rack-cors'  # コメントアウトを外す
api $ bundle install

cors.rbを修正していきます。

api/config/initializers/cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins ENV["API_DOMAIN"] || 'localhost:8080'

    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

origins ENV[“API_DOMAIN”] || ‘localhost:8080’ の記述で環境変数API_DOMAINまたはlocalhost:8080からのアクセスを許可します。

今回はAPI_DOMAINについては設定しません。

corsの設定が完了したので再度railsとnuxtのサーバーを起動し直して「GET API」ボタンをクリックします。

下記のようにボタンをクリックで「Hello Rails」の文字が表示されれば完成です。

これでAPI通信の機能は実装できました。

ここからはユーザーの登録ができるように行っていきますが、代表的なところでいうとdevise_token_authを使用した方法とfirebaseを使用した方法があるのでこの2つのパターンで登録する方法を記事にしたのでどちらか好きな方法を選んでください。

devise_token_authはこちら: coming soon…

firebaseはこちら: Nuxt + Rails + Firebase ユーザー登録 (Nuxt編)

Rails + Nuxtカテゴリの最新記事