LoginSignup
2
3

More than 1 year has passed since last update.

[React/Rails] WebSocket connection to 'ws://localhost:3000/ws' failed が発生してレスポンスが受け取れない

Posted at

動作環境

MacOS M1 BigSur 11.6
Docker "20.10.8"
node "14.17.5"
yarn "1.22.5"
react-scripts "5.0.1"
axios "^0.27.2"
Rails "6.1.6" APIモード

結論

Reactのルートディレクトリ直下に.envファイルを作成し、下記の記述をする

/.env
WDS_SOCKET_PORT=0

エラー内容

React/TypeScriptで作成したアプリケーションからRailsのAPIへリクエストを送信したところ下記エラーが発生した。
スクリーンショット 2022-06-20 22.41.31.png

WebSocket connection to 'ws://localhost:3000/ws' failed

コード

(とりあえず動かしたかったので型定義は最低限しかしてません)

src/App.tsx
import React, { useState, useEffect } from 'react';

const api = axiosBase.create ({
  baseURL: 'http://localhost:3000/dailies',
  responseType: "json",
})

const Request = async() =>{
  return await api.get('/')
}

const App: React.FC = () =>  {
  const [res, setRes] = useState([])

  useEffect(() => {
    Request().then((res: any) => {
      setRes(res.data)
    })
  },[])
  console.log(res)
  
  return(
    省略
  )

下記のようにブラウザからリクエストを送るとちゃんとレスポンスが返ってくる
image.png

試したけどダメだったこと

Railsのcorsの設定が正しくできているか確認する

/config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'http://localhost:8000' # ここをReactを立ち上げているサーバーのPortに設定

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

=> 結果変わらず

参考リンク

上記Githubのissueを隅から隅まで探した結果、無事解決しました。
Websocketがなんだかよくわかっていないので、引き続き勉強します。
ちなみにreact-scriptsのバージョン5.0以降に発生するらしい。

2
3
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
2
3