本文由 简悦 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=["*"],
)
标签:http,跨域,origins,fastAPI,博客,com,localhost,backend
From: https://www.cnblogs.com/zhuoss/p/16876843.html