Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get CORS Error Reason: CORS request did not succeed

I am developing a svelte app which uses a FastAPI backend to interact with a PostgreSQL database which is local to my organization, not on my AWS EC2 instance.

I use javascript's fetch api to send requests to my backend to query the database for various things, on my local machine all of these requests are received on both ends, on AWS however the requests from my frontend are not even recognized by the fastAPI backend.

I am fairly inexperienced with setting up servers like this so I assume there is some basic mistake in my setup of these servers that makes communication between them on AWS like this impossible.

The fastapi code looks like this:

import uvicorn
from fastapi import (Depends, FastAPI, HTTPException, Query,
                     Request)
from fastapi.middleware.cors import CORSMiddleware


app = FastAPI(debug=True)

origins = [
    '*'
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
async def root():
    return {"message": "Hello World"}

if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=8000)

My fetch requests look like this typically:

const endpoint = public_IP:8000 + `/`;

let objs = [];

fetch(endpoint)
    .then(response => {
        if (!response.ok) {
            throw Error(response.statusText);
        }
        return response.json();
    })

When I send a fetch request like the above one I get a CORS error with reason: CORS request did not succeed. The FastAPI server, has no feedback, the request never seems to reach it, I am unsure why. As far as I know this usually has to do with issues between requests with HTTP and HTTPS, but these don't seem relevant to my issue as no part of my setup is not using HTTP. When using chrome I get the error: Failed to load resource: net::ERR_CONNECTION_REFUSED as well.

My AWS security groups for my EC2 instance allow TCP trafic from any IP to ports 5000 and 8000. Which is where my two apps are hosted, Svelte and FastAPI respectively.

like image 619
Warren Avatar asked Aug 26 '20 21:08

Warren


1 Answers

Most likely, your endpoint in the fastapi app is raising an exception. When this arise, the CORSMiddleware installed via app.add_middleware(...) does not see any HTTP response and has no chance to do its job on the HTTP response produced by FastAPI error handler.

The solution is to wraps the whole FastAPI app with the CORSMiddleware as in :

import uvicorn
from fastapi import (Depends, FastAPI, HTTPException, Request
from fastapi.middleware.cors import CORSMiddleware


app = FastAPI(debug=True)

origins = [
    '*'
]


@app.get("/")
async def root():
    return {"message": "Hello World"}


app = CORSMiddleware(
    app=app,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

if __name__ == '__main__':
    uvicorn.run(app, host="0.0.0.0", port=8000)
like image 184
Thomasleveil Avatar answered Oct 07 '22 14:10

Thomasleveil