Home > OS >  How do get rid of cors-error in dockerized multi-container app in AWS-fargate?
How do get rid of cors-error in dockerized multi-container app in AWS-fargate?

Time:09-03

I am trying to deploy my app (two containers) - backend python:fastapi , frontend:vue.js - to aws fargate. Locally, everything is working well (frontend-container on port 80 and backend-container on port 8080) , but as soon as I am running everything on AWS the browser console shows the following error:

Access to XMLHttpRequest at "http://127.0.0.1:8080/api/" from origin 'http://ec2-3-65-218-102.eu-central-1.compute.amazonaws.com' has been blocked by CORS policy: The request client is not a secure context and the resource is in more-private address space 'local'.

The frontend container can be reached from the internet and works (showing some static content). I am running both containers inside the same task, so in my opinion 127.0.0.1:8080 should trigger the local loopback interface to the backend-container (container port 8080 ist open in the task definition and also exposed in the docker file)-- since I am pretty new to AWS , I am not sure whether this actually takes place. Also , the fastapi configuration in main.py should in general allow for CORS :

from starlette.middleware.cors import CORSMiddleware

from app.routes import views

print("Start API")
app = FastAPI()

# Set all CORS enabled origins
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(views.router)

As I am running out of ideas, I was wondering whether I am missing sth. obvious to someone else ?

CodePudding user response:

That error states that the front-end code is still trying to access your local back-end API, instead of the API on AWS.

This is incorrect:

I am running both containers inside the same task, so in my opinion 127.0.0.1:8080 should trigger the local loopback interface to the backend-container

The front-end code doesn't run on AWS. Your Vue app container is just serving HTML/CSS/JavaScript files to the web browser. The code itself runs inside the web browser. Making a request to 127.0.0.1 from the web browser means that it will try to access that service on the same computer/laptop that the web browser is running on.

So before you continue you will need to fix your setup so that the back-end API is exposed to the Internet so it can actually be accessed from the web browser, and fix the address you are using in the front-end code to access the backend.

  • Related