0

I'm trying to get a fastapi deployed (usually work in Node) and I'm getting a CORS error consistently. I've tried, wildcarding, I've tried explicit URL lists. No change no matter which I do.

The root serves Swagger docs which are deployed, and the test of all endpoints are working as espected.


API = FastAPI(
    title="DocDB DS API",
    version="1.0.0",
    docs_url="/",
)
API.db = MongoDB()
API.s3 = S3()


API.add_middleware(
    CORSMiddleware,
    allow_origins=["https://examplevercelurl.app"],
    allow_credentials=True,
    allow_methods=["GET", "POST", "DELETE", "PUT"],
    allow_headers=["*"],
)


@API.get("/version")
async def version():
    return API.version


@API.post("/search")
async def search(query: str, page_number: int = 0, results_per_page: int = 100):
    start = page_number * results_per_page
    stop = start + results_per_page
    search_results = API.db.search(query)[start:stop]
    count = API.db.count({"$text": {"$search": query}})
    n_pages = ceil(count / results_per_page)
    return {"Pages": n_pages, "Count": count, "Response": list(search_results)}

The console produces this error:

Access to XMLHttpRequest at 'https://example.herokuapp.com/search?query=gun&page_number=0&results_per_page=20' from origin 'https://examplevercelurl.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The client is hosted at https://examplevercelurl.app (cannot provide actual URL but I have made sure once again that the address listed in the origins list is correct)

Jason Long
  • 71
  • 3
  • 9
  • 1
    How exactly are you attempting to consume these endpoints? Are you using JavaScript? – MrFlick Aug 29 '23 at 22:56
  • I am attempting to hit the search endpoint from a React application. – Jason Long Aug 29 '23 at 23:07
  • Related answers can be found [here](https://stackoverflow.com/a/71805329/17865804), [here](https://stackoverflow.com/a/73963905/17865804), as well as [here](https://stackoverflow.com/a/75041731/17865804) and [here](https://stackoverflow.com/a/75048778/17865804). You might also find [this](https://stackoverflow.com/a/74163726/17865804) and [this](https://stackoverflow.com/a/76768156/17865804) helpful. – Chris Aug 30 '23 at 04:39
  • 1
    You write: _I'm getting a CORS error consistently_. The error message would likely be useful, yet it is nowhere to be seen in your question. – jub0bs Aug 30 '23 at 07:17
  • 2
    Examples of the request and the response that generates the CORS issue (including which domains the request is coming from) would also be useful. Remember that if the service responds with an error (500 for example), CORS headers will not be added. – MatsLindh Aug 30 '23 at 07:42
  • Unfortunately Chris, I'd seen all of those and don't resolve the issue, but thank you. – Jason Long Aug 30 '23 at 14:15

0 Answers0