关于fastapi的cors问题,没想到fastapi都写到文档里面了,实现起来也非常简单:
StackOverflow:
https://stackoverflow.com/questions/65635346/how-can-i-enable-cors-in-fastapi
python代码如下:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
async def main():
return {"message": "Hello World"}
然后运行这个代码:
uvicorn main:app --reload --host 0.0.0.0 --port 8000
然后在html里面加入下面的代码(注意ip和端口)测验一下:
<script>
fetch("http://192.12.12.12:8000/").then((Response) => {
return Response.json()
}).then((data) => {
console.log(data);
})
</script>