美文网首页
Fastapi 跨域保存response cookie问题

Fastapi 跨域保存response cookie问题

作者: 劉小乙 | 来源:发表于2022-03-03 21:14 被阅读0次

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

相关文章

网友评论

      本文标题:Fastapi 跨域保存response cookie问题

      本文链接:https://www.haomeiwen.com/subject/vwburrtx.html