fastAPI中的跨域问题解决

CrossOrigin

前言

前端采用Vue,后端采用fastAPI的CV项目在开发时遇到跨域问题,记录学习过程与解决方案。

概念

  • CORS

CORS or “Cross-Origin Resource Sharing” refers to the situations when a frontend running in a browser has JavaScript code that communicates with a backend, and the backend is in a different “origin” than the frontend.

  • Origin

An origin is the combination of protocol (http, https), domain (myapp.com, localhost, localhost.tiangolo.com), and port (80, 443, 8080).

Then, the browser will send an HTTP OPTIONS request to the backend, and if the backend sends the appropriate headers authorizing the communication from this different origin (http://localhost:8080) then the browser will let the JavaScript in the frontend send its request to the backend.

  • Preflight Request

These are any OPTIONS request with Origin and Access-Control-Request-Method headers.

解决方法

采用CORS中间件,后端添加allowed origins列表

from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

// 配置允许域名
origins = [
    "http://localhost.tiangolo.com",
    "https://localhost.tiangolo.com",
    "http://localhost",
    "http://localhost:8080",
]
// 配置允许域名列表、允许方法、请求头、cookie等
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值