本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net
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=["*"], )
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!