0
0

RailsとNext.jsの連携(SPA)

Posted at

この記事の概要

RailsとNext.jsのSPAの連携方法に絞ってこちらの記事を書いていきます。

Gemfileにrack-corsを追加

以下のようにまず、Gemを入れます。

gem 'rack-cors'

その後に

bundle install

をします。

CORS設定ファイルを作成または編集

config/initializers/cors.rbファイルを作成または編集します。

config/initializers/cors.rb
# Be sure to restart your server when you modify this file.

# Avoid CORS issues when API is called from the frontend app.
# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests.

# Read more: https://github.com/cyu/rack-cors

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'http://localhost:3001' # Next.jsアプリが動作するURLを指定

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

CORS設定を反映させるために、Railsサーバーを再起動します。

$ rails server

Next.jsアプリケーションからのAPI呼び出す

ここからNext.jsを使ってRailsのAPIを呼び出したいと思います。
今現在はレストラン一覧が表示されるだけの状態です。

src/containers/Restaurants.tsx
import React, { useEffect } from 'react';

const Component = () => {
  return (
    <>
      レストラン一覧
    </>
  );
};

これを以下のように追記します。

src/apis/restaurants.ts
import React, {useEffect} from 'react';

//api
import { fetchRestaurants } from '../apis/restaurants';

export const Restaurant = () => {
  useEffect(() => {
    fetchRestaurants()
    .then((data)=>
      console.log(data)
    )
  },[])
    return (
        <>
          レストラン一覧
        </>
      );
}

すでに作成したファイリ達です。

src/apis/restaurants.ts
import axios from 'axios';
import { restaurantsIndex } from '../urls/index'

export const fetchRestaurants =() => {
  return axios.get(restaurantsIndex)
  .then(res => {
    return res.data
  })
  .catch((e) => console.error(e))
}
src/urls/index.ts
const DEFAULT_API_LOCALHOST = 'http://localhost:3000/api/v1';

export const restaurantsIndex = `${DEFAULT_API_LOCALHOST}/restaurants`;
export const foodsIndex = (restaurantId: number) =>
  `${DEFAULT_API_LOCALHOST}/restaurants/${restaurantId}/foods`;
//省略

ここで、Next.jsアプリケーションのルートページでRestaurantsコンポーネントを使用しています。

pages/restaurants.tsx
import { Restaurant } from '../containers/Restaurants';

const RestaurantsPage  = () => {
    return <Restaurant />;
  };
  
  export default RestaurantsPage;

動作確認

Rails側で

rails server

Next.js側で

npm run dev

です。

スクリーンショット 2024-08-05 2.30.49.png

しっかりデータが取れていました。

SPAを学べる教材

Techpitでよく学べるので、よかったら学んでください。

0
0
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
0
0