Docker上でReactとRails(+DB)、nginxを動かしているのですが、ReactからRails API modeにFetchを送っても届きません。
React側では以下のようなメソッドを実行しています
172.19.0.3はRailsのコンテナのIPアドレスです
JavaScript
1 handleGet() { 2 fetch('http://172.19.0.3:3001/users') 3 .then(response => { 4 return response.json(); 5 }) 6 .then(json => { 7 console.log(json); 8 }) 9 }
Rails(API)側ではこのような実装です
Ruby
1 # GET /users 2 def index 3 @users = User.all 4 5 render json: @users 6 end
corsの許可は以下のようにしています(nginxのIPアドレス)
Ruby
1 config.action_dispatch.default_headers = { 2 'Access-Control-Allow-Origin' => 'http://172.19.0.5:80', 3 'Access-Control-Request-Method' => '*' 4 }
React側のコンテナに入りcurlでAPIにアクセスするとjsonが返ってくるのですが、実際にブラウザからの操作でFetchを投げるとエラーになります
bash
1$ curl http://172.19.0.3:3001/users #正常に動作する
ブラウザのコンソール
GET http://172.19.0.3:3001/users 0 () ncaught (in promise) TypeError: Failed to fetch
ちなみに、外部レンタルサーバーにjsonを返すPHPファイルを設置しアクセスしたところ、正常に動作したのでDockerでの問題と思われます。IPアドレスをlocalhostにしてもダメでした。
解決方法ご存知の方いらっしゃいましたらよろしくお願いいたします…
docker-compose.ymlです
yml
1version: '3' 2 3volumes: 4 store: 5 driver: local 6 bundle: 7 driver: local 8 9services: 10 nginx: 11 build: ./nginx 12 ports: 13 - 8080:8080 14 expose: 15 - "8080" 16 volumes: 17 - ./frontend/dist:/wwwroot:ro 18 links: 19 - web 20 frontend: 21 build: ./frontend 22 volumes: 23 - ./frontend/src:/app/src 24 - ./frontend/dist:/app/dist 25 links: 26 - web 27 web: 28 build: . 29 ports: 30 - 3001:3001 31 expose: 32 - "3001" 33 volumes: 34 - .:/app 35 - bundle:/usr/local/bundle 36 links: 37 - db 38 stdin_open: true 39 tty: true 40 command: ./scripts/backend.sh 41 environment: &app_env 42 PORT: 3001 43 DB_HOST: db 44 DB_PORT: 5432 45 DB_NAME: rails_docker_database 46 DB_USER: postgres 47 DB_PSWD: postgres 48 db: 49 image: postgres:latest 50 ports: 51 - 5432:5432 52 volumes: 53 - store:/var/lib/postgresql/data 54 environment: 55 POSTGRES_USER: postgres 56 POSTGRES_PASSWORD: postgres 57 POSTGRES_DB: rails_docker_database
回答2件
あなたの回答
tips
プレビュー