0

I have an API built in FastAPI hosted with uvicorn. I also have a website build in next.js. My typical workflow is to run the API locally on the command line and it will be hosted on localhost:8000, then run the website on the command line and point it at the API at the above address. The website runs at localhost:3000.

If I run the API on the command line, this all works fine, no CORS issues. My API is currently set up super-permissive for now:

    cors_app = CORSMiddleware(app=app, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"])

    uvicorn.run(
        cors_app,
        host="0.0.0.0",
        port=8000,
        log_config=LOGGING_CONFIG,
    )

However, if I want to debug the API, I can run it with this launch.json entry:

    {
      "name": "Python Debugger: FastAPI",
      "type": "debugpy",
      "request": "launch",
      "module": "uvicorn",
      "args": ["services.api.app.main:app", "--reload"], 
    }

When I do, everything seems fine, but all front-end fetch commands suddenly throw 405 CORS Errors:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Why is this only happening when I run out of VSCode with the debugpy debugger? It runs the exact same server setup code and has the same CORS configured so it makes now sense that running it in the debugger should surface new CORS issues....

How can I fix it?

1
  • Please see if the following posts can help you resolve the issue: this, this and this Commented Feb 5 at 19:02

1 Answer 1

0

Test your API with curl or Postman to determine whether the issue lies with your API or your front-end code.

Additionally, try to use add_middleware as described in fastapi docs:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

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


@app.get("/")
async def main():
    return {"message": "Hello World"}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.