Description I have a React application that makes the following request:
await axios.get(`${process.env.REACT_APP_MASTER_HOST}/api/agl-history`, { headers: { Authorization: `Bearer ${token}` }, data: { label, date } });
In some cases it works but when the backend is started with docker-compose up -d
, it gives me the following in Chrome:
Access to XMLHttpRequest at 'http://localhost:8080/api/agl-history' 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.
When it works
- When I manually build the image with
sudo docker build . -t test
and run,sudo docker run -p 8080:8080 -t test
, it works perfectly - When I run the flask server with
flask run --host=0.0.0.0
When it does not work
docker-compose up -d
// docker-compose.yml, relevant service is master
version: "3.9"
services:
agl-history:
depends_on:
- mariadb
build: ./agl-history
restart: on-failure
networks:
- main
master:
depends_on:
- mariadb
build: ./master
restart: on-failure
ports:
- 8080:8080
networks:
- main
mariadb:
image: "mariadb:10.5.10"
restart: on-failure
environment:
MYSQL_ROOT_PASSWORD: ${MARIADB_PASSW}
ports:
- 3306:3306
volumes:
- /var/lib/docker/volumes/add3-data:/var/lib/mysql
networks:
- main
networks:
main:
driver: bridge
// Dockerfile
FROM python:3.9.5-buster
WORKDIR /app
COPY requirements.txt requirements.txt
RUN pip3 install -r requirements.txt
COPY . .
ENV FLASK_RUN_PORT 8080
ENV FLASK_APP source/server_config.py
CMD [ "python3", "-m" , "flask", "run", "--host=0.0.0.0"]
// Flask endpoint
from datetime import date
from flask import Flask
from flask import jsonify
from datetime import datetime
from flask_cors import CORS
# app reference
app = Flask(__name__)
cors = CORS(app)
# This method executes before any API request
@app.before_request
def before_request():
print('before API request')
@app.route('/api/agl-history', methods=['GET'])
def get_agl_history():
print('during')
response = jsonify([
{
'id': 1,
'customerId': 777,
'campaignName': 'Test campaing',
'adGroupName': 'Test ad group',
'execDate': datetime.now(),
'label': '92'
}
]
)
return response
# This method executes after every API request.
@app.after_request
def after_request(response):
return response
Notes
- React frontend and server backend is going to be run on different hosts eventually
What am I doing wrong? Any help is greatly appreciated! Thanks!