質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Ruby on Rails 6

Ruby on Rails 6は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Amazon EC2

Amazon EC2は“Amazon Elastic Compute Cloud”の略称です。Amazon Web Services(AWS)の一部であり、仮想化されたWebサーバーのコンピュータリソースをレンタルできるサービスです。

CORS

CORSとはCross-Origin Resource Sharingの頭文字をとったもので、ブラウザがオリジン以外のサーバからデータを取得するシステムのことです。

React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

Q&A

解決済

1回答

2917閲覧

本番環境(EC2)にデプロイしたら、CORS policy のエラーでフロントとAPIで通信できない

gozikyu

総合スコア4

Ruby on Rails 6

Ruby on Rails 6は、オープンソースのWebアプリケーションフレームワークです。「同じことを繰り返さない」というRailsの基本理念のもと、他のフレームワークより少ないコードで簡単に開発できるよう設計されています。

Amazon EC2

Amazon EC2は“Amazon Elastic Compute Cloud”の略称です。Amazon Web Services(AWS)の一部であり、仮想化されたWebサーバーのコンピュータリソースをレンタルできるサービスです。

CORS

CORSとはCross-Origin Resource Sharingの頭文字をとったもので、ブラウザがオリジン以外のサーバからデータを取得するシステムのことです。

React.js

Reactは、アプリケーションのインターフェースを構築するためのオープンソースJavaScriptライブラリです。

0グッド

1クリップ

投稿2021/04/02 09:55

以下の内容で開発をしており、EC2上にデプロイをしたのですが、corsのエラーでフロ ントエンドからAPIにリクエストを投げてもレスポンスを受け取れないで困っております。

フロントエンド:react ポート3000で起動
API:rails apiモード ポート3001で起動
docker-compose を用いてフロントエンド、API用のコンテナをそれぞれ起動させています。

①reactのsignIn.jsx上でhttp://52.195.8.187:3001/loginに対して postメソッドでリクエストを投げる
②APIのログは以下の通り、ステータスは200になっているので、APIには届いている (と考えています)
https://gyazo.com/c3918eb83e08ac6749d4f50a84017cf0
③しかし、フロントエンド(ブラウザ上)では以下の通り、エラーが出てしまっている。つまり、レスポンスは返してるけど、フロントエンドまで届いていない(と考えています)
エラー内容
https://gyazo.com/e403ad25d66c10dc80b055362ff7b44a

試したこと
Access-Control-Allow-Credentials がtrueでないといけないとエラー分に書いておりましたので、以下のようにconfig/application.rbに設定を追加しましたが、同様のエラーが発生しました。

config.action_dispatch.default_headers = { 'Access-Control-Allow-Credentials' => 'true', 'Access-Control-Allow-Origin' => 'http://52.195.8.187:3000', 'Access-Control-Request-Method' => '*' }

cors.rbについても、設定を有効にしているのですが、エラーが出てしまいます。

ご知見ある方いらっしゃいましたらアドバイスいただけると幸いです。

どうぞよろしくお願いいたします。

signIn.jsx

import React, { useCallback, useState } from "react"; import { TextInput, PrimaryButton } from "../UIkit/index"; import axios from "axios"; import { useHistory } from "react-router-dom"; const SignIn = (props) => { const history = useHistory(); const [email, setEmail] = useState(""), [password, setPassword] = useState(""); const signIn = () => { axios .post( "http://52.195.8.187:3001/login", { user: { email: email, password: password, }, }, { withCredentials: true } ) .then((response) => { console.log("registration res", response); const createdId = response.data.id; console.log(createdId); props.login(); history.push({ pathname: "/users/" + createdId }); }) .catch((error) => { console.log("registration error", error); alert("メールアドレスとパスワードの組み合わせが正しくありません。"); }); }; const inputEmail = useCallback( (event) => { setEmail(event.target.value); }, [setEmail] ); const inputPassword = useCallback( (event) => { setPassword(event.target.value); }, [setPassword] ); return ( <div className="c-section-container"> <h2 className="u-text__headline u-text-center">ログイン</h2> <div className="module-spacer--medium" /> <TextInput fullWidth={true} label={"メールアドレス"} multiline={false} rows={1} required={true} value={email} type={"email"} onChange={inputEmail} /> <TextInput fullWidth={true} label={"パスワード"} multiline={false} rows={1} required={true} value={password} type={"password"} onChange={inputPassword} /> <div className="guestAccount"> <h3>ゲストアカウント</h3> <p>メールアドレス: guest@gmail.com</p> <p>パスワード: password</p> </div> <div className="module-spacer--medium" /> <div className="center"> <PrimaryButton label={"ログインする"} onClick={() => signIn()} /> <div className="help"> <p onClick={() => history.push("/signup")}> アカウントをお持ちでない方はこちら </p> </div> </div> </div> ); }; export default SignIn;

config/application.rb

require 'action_mailer/railtie' require 'action_mailbox/engine' require 'action_text/engine' require 'action_view/railtie' require 'action_cable/engine' # require "sprockets/railtie" require 'rails/test_unit/railtie' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module Myapp class Application < Rails::Application # Initialize configuration defaults for originally generated Rails version. config.load_defaults 6.1 # Configuration for the application, engines, and railties goes here. # # These settings can be overridden in specific environments using the files # in config/environments, which are processed later. # # config.time_zone = "Central Time (US & Canada)" # config.eager_load_paths << Rails.root.join("extras") # 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 0, Rack::Cors do allow do origins 'http://52.195.8.187:3000' resource '*', headers: :any, methods: %i[get post patch delete options], credentials: true end end config.hosts << "52.195.8.187" # セッションメソッドを有効にする config.middleware.use ActionDispatch::Cookies config.middleware.use ActionDispatch::Session::CookieStore config.middleware.use ActionDispatch::ContentSecurityPolicy::Middleware config.time_zone = 'Tokyo' config.active_record.default_timezone = :local config.action_dispatch.default_headers = { 'Access-Control-Allow-Credentials' => 'true', 'Access-Control-Allow-Origin' => 'http://52.195.8.187:3000', 'Access-Control-Request-Method' => '*' } end end

cors.rb

# frozen_string_literal: true # 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://52.195.8.187:3000' resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head] end end

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

自己解決

以下のように cors.rbにcredensials: trueを追加することで解決しました

Rails.application.config.middleware.insert_before 0, Rack::Cors do allow do origins 'http://' resource '*', headers: :any, methods: [:get, :post, :put, :patch, :delete, :options, :head], credentials: true end end

投稿2021/04/02 11:57

gozikyu

総合スコア4

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問