Hello, I currently have a Flask/React App that I am using in tandem with Docker. I wrote Dockerfiles for both the backend (Flask) and frontend (React), and a docker-compose.yml to combine the two together and initialize my app when I use the command “docker-compose up”.
I am able to start the app correctly, but when I try to login and send the api request to the backend, I am presented with the following CORS error:
Access to XMLHttpRequest at 'http://127.0.0.1:5000/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I am not having this error in my application when run out of the containers, so I am pretty positive it is related to the configuration of the Dockerfiles/ports. Here are my Dockerfiles and the docker-compose.yml. I know my flask app itself is configured with CORS to avoid this error when the app is not run in the container.
Backend
FROM python:3
WORKDIR /app
ENV FLASK_APP=main.py
COPY ./requirements.txt .
RUN pip install -r requirements.txt
COPY . .
CMD ["python", "main.py"]
Frontend
FROM node:14-slim
WORKDIR /user/src/app
COPY ./package.json ./
COPY ./package-lock.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
Docker-Compose
version: "3.9"
services:
server:
build: ./backend
ports:
- "80:5000"
volumes:
- ./backend:/app
environment:
FLASK_ENV: development
web:
build: ./frontend
ports:
- "3000:3000"
volumes:
- ./frontend:/user/src/app
depends_on:
- server
Below is the partial frontend JavaScript function that handles the data being sent to the backend:
const handleSubmit = async (event) => {
try {
event.preventDefault()
const payload = {name:username, password:password}
const response = await axios.post("http://127.0.0.1:5000/login", payload, {headers:{
'Access-Control-Allow-Origin' : '*',
'Content-Type': 'application/json'
}})
Any folks out there have encountered a similar issue and may have potential recommendations?