LoginSignup
30
24

More than 5 years have passed since last update.

RailsのAPIモードとReact.jsチュートリアルを連携してみた。

Posted at

概要

Rails(APIモード)を利用してJSONを書き出すAPIサーバを準備し、React-tutorialと連携をしてみる。

動作環境

macOS Sierra
npm 4.0.5
Ruby 2.3.3
Rails 5.0.2

Railsの設定(APIサーバの準備)

プロジェクト作成 & scaffold

$ rails new react-api --api && cd react-api
$ rails g scaffold comment author:string text:text
$ rails db:migrate

(DBはSQLiteを使用)

seedファイル作成

db/seed.rb
Comment.delete_all
Comment.create!([
  { author: 'サンプル1', text: 'sample01 book' },
  { author: 'サンプル2', text: 'sample02 note' },
  { author: 'サンプル3', text: 'sample03 ofuda' },
])
$ rails db:seed

Header情報の設定。

別ドメインのクライアントからJsonを取得可能にするためのHeader情報を設定する。

Gemfileにイカ

Gemfile
gem 'rack-cors', :require => 'rack/cors'
$ bundle
config/application.rb
module RailsApi
  class Application < Rails::Application
    # Settings in config/environments/* take precedence over those specified here.
    # Application configuration should go into files in config/initializers
    # -- all .rb files in that directory are automatically loaded.

    # Only loads a smaller set of middleware suitable for API only apps.
    # Middleware like session, flash, cookies can be added back manually.
    # Skip views, helpers and assets when generating a new resource.
    config.api_only = true

    # 以下追記
    config.middleware.insert_before ActionDispatch::Static, Rack::Cors do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :delete]
      end
    end

  end
end

Reactから送られてくるデータの処理を追加する。

/comments への postデータは comments#create で処理をするように設定する。

config/routes.rb
post '/comments', to: 'comments#create'
  1. 受け取ったデータから登録ができるように処理を追加する。
  2. Reactのサンプルに合わせて、返り値の値を単体から複数に変更。
app/controllers/comments_controller.rb
def create
  @comment = Comment.new(author: params[:author], text: params[:text])
  if @comment.save
    comments = Comment.all
    render json: comments, status: :created, location: @comment
  else
    render json: @comment.errors, status: :unprocessable_entity
  end
end

注)Strong Parametersをスキップしてるので、修正が必要。

サーバ起動

$ rails s -p 3001

注)運用する場合には認証設定が必要です。

フロント設定(Reactチュートリアル)

React チュートリアルのサンプルファイルのダウンロード

$ git clone https://github.com/reactjs/react-tutorial.git
$ cd react-tutorial
$ npm install

URLの修正

ReactDOM.render(
  <CommentBox url="http://localhost:3001/comments" pollInterval={2000} />,
  document.getElementById('content')
);

フロントサーバ起動

$ ruby server.rb

あとは、http://localhost:3000 へアクセスする。

30
24
0

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
30
24