【FastAPI】跨域资源共享

什么是跨域资源共享

浏览器资源安全的一个方案,使开发的接口,不会被其他网站滥用,需要满足你指定的条件网站才能使用

条件可以指定:请求方法头部信息

使用

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

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=[  # 允许访问的域 域 --> 协议:域名:端口
        'http://127.0.0.1',
        'http://127.0.0.1:8000',
    ],
    allow_methods=['*', 'GET'],  # * 可以通配
    allow_headers=['*'],  # 头部
    allow_credentials=False,  # HTTPS 证书
    allow_origin_regex=None,  # 正则表达式匹配  'https://.*\.example\.org
    expose_headers=[],  # 指明可以被 浏览器访问 的 响应头
    max_age=600  # 设定浏览器缓存 CORS 响应的最长时间,单位是秒。默认为 600
)

@app.get("/")
async def main():
    return {"message": "Hello World"}

if __name__ == '__main__':
    uvicorn.run(app)
发表评论 / Comment

用心评论~