0

I have 2 docker containers, one running React App and the other one running Node Express API. Here is my docker-compose.yml file:

version: '3.8'

services:
  node-api:
    build: ./node-api
    ports:
      - 9000:9000
    restart: 
      on-failure

  react-app:
    build: ./react-app
    ports:
      - 3000:3000
    depends_on:
      - node-api

When I try calling an API with fetch, I get 'CORS request did not succeed' error. CORS is enabled on the backend:

const express = require("express");
const cors = require("cors");

const app = express();
app.use(cors());

Here is also a function inside React App that calls API:

const handleContentClick = async () => {
   let url = `http://node-api:9000/api/content`;
   const response = await fetch(url);
   const data = await response.json();
}

I tried explicitly setting CORS origin to react-app container, but that did not help.

One thing that confuses me is when I enter react-app container and try accessing an API with curl or node, I get the response from API. Why is it reachable from the same container via node and curl, but not from React App?

I also tried replacing fetch with axios, but I still got an error (this time it is ERR_NETWORK error).

Also, everything worked fine when I ran this on my local machine, but once I tried running it on a remote host, these errors appeared.

Do you have any suggestions?

0

1 Answer 1

3

React APP is served by a container, but it's rendered in the browser, I image at localhost:3000.

node-api backend is exposed from docker container to localhost:9000, so the url to be used in react should be: http://localhost:9000/api/content

and CORS should be configured to allow localhost:3000

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.