vuejs において、fastapiデータを受信しようとしたがCORSによりエラーでたことの対応 CORS CORS

vuejs において、fastapiデータを受信しようとしたがCORSによりエラーでたことの対応


★エラー内容
vuejs環境において、fastapi側から データを受信してデータを表示しようとすると
以下のエラーがでる。

Access to fetch at 'xxxx' from origin 'yyyy' has been blocked by CORS policy:
Response to preflight request doesn't pass access control check:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

解決策として
fastapi/main.py と vite.config.ts を修正すると、エラー回避しデータ表示できるようになった。


★修正ファイル1 fastapi main.py ファイル
from starlette.middleware.cors import CORSMiddleware # CORS対応 追加

app.add_middleware(
CORSMiddleware,
allow_origins=["http://xxx.xxx.xxx.xxx:xxxx"], # vuejs ipaddress front側のvuejsの ipアドレスを書く(python側ではないよ)
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)


★修正ファイル2 vue frontend側 "vite.config.ts" ファイルを修正
export default defineConfig({
server: {
proxy: {
'/api': { ★★
target: 'http://xxx.xxx.xxx.xxx:xxxx', // 受信するAPIサーバ(fastapi)の向き先 ★★
changeOrigin: true, // オリジンを変更する場合は true
rewrite: (path) => path.replace(/^\/api/, ''), // パスのリライト ★★
},
},
},