fastapi必须使用CORSMiddleware允许浏览器跨域访问,并使用JSONResponse返回set-cookie
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
origins=[
"http://localhost",
"http://127.0.0.1:5500",
"http://127.0.0.1"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins, #允许访问的源
allow_credentials = True,#支持cookie
allow_methods=["*"],#允许使用的方法
allow_headers=["*"] #允许携带的头部
)
#使用JSONResponse返回response的set-cookie
content = jsonable_encoder({"access_token":access_token,"token_type":"bearer"})
# headers = {"set-cookie":user.username}
response = JSONResponse(content=content)
response.set_cookie(key="username",value=user.username)
return response