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?