最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - My FastAPI service is giving CORS errors from my website running on localhost when I run the API in VSCode, but not if

programmeradmin0浏览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?

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?

Share Improve this question asked Feb 5 at 18:00 Clayton StetzClayton Stetz 1 1
  • Please see if the following posts can help you resolve the issue: this, this and this – Chris Commented Feb 5 at 19:02
Add a comment  | 

1 Answer 1

Reset to default 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"}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论