https://cloud.tencent.com/developer/article/1884129
https://cloud.tencent.com/developer/article/1884130
https://cloud.tencent.com/developer/article/1886112
需要先了解什么是同源策略、CORS、跨域报错栗子才能更好看懂这篇文章
'https://example.org', 'https://www.example.org'
'*'
'GET'
'*'
[]
'*'
[]
#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# author: 小菠萝测试笔记
# blog: https://www.cnblogs.com/poloyy/
# time: 2021/9/28 12:58 下午
# file: 33_cors.py
"""
import uvicorn
from fastapi import FastAPI, Body
# 1、导入对应的包
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# 2、声明一个 源 列表;重点:要包含跨域的客户端 源
origins = [
"http://localhost.tiangolo.com",
"https://localhost.tiangolo.com",
"http://localhost",
"http://localhost:8080",
# 客户端的源
"http://127.0.0.1:8081"
]
# 3、配置 CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=origins, # 允许访问的源
allow_credentials=True, # 支持 cookie
allow_methods=["*"], # 允许使用的请求方法
allow_headers=["*"] # 允许携带的 Headers
)
# 模拟服务端 登录 接口
@app.post("/login")
def get_login(id: str = Body(...), name: str = Body(...)):
return {"id": id, "name": name}
if __name__ == '__main__':
# 服务端端口是 8080!
uvicorn.run(app="33_cors1:app", reload=True, host="127.0.0.1", port=8080)
看看 preflight 预检请求的响应
这些就是 FastAPI 服务端设置的
至此!现在可以正常跨域发起请求啦!
至此!现在可以正常跨域发起请求啦!
至此!现在可以正常跨域发起请求啦!