简体   繁体   中英

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.

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)

Summary

CORS errors are can be so confusing sometimes because, the error messages are not clear enough and there is a lot of possible solutions.

First possibility

  • If you load your page from a given host, in your case 0.0.0.0 and then try to make an request to another host, for example 127.0.0.1 , the request gets blocked to prevent XSS attacks

Changing your host from 0.0.0.0 to 127.0.0.1 should fix this.

Second possibility

If you are a Mozillian, there is bug(s)[ see , see ] in Mozilla, but if this the case your code should be working in other browser

Solution: You must enable the certificate on each port indivually.

Other possibilities

Try changing your endpoint this

const endpoint = public_IP:8000 + `/`;

to this

const endpoint = `/`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM