async load_disp_date_range(vue_obj){ let req_url = this.server_api_base() + "DispDateRange"; let res = await fetch(req_url); let disp_dates = await res.json(); vue_obj.disp_date_min = disp_dates[0]; vue_obj.disp_date_max = disp_dates[1]; vue_obj.disp_date = disp_dates[1]; }
fetch() for javascript を用い、他のサーバへ、ajax requestすると、以下のエラー。
Access to fetch at 'http://localhost:8080/api/newbuild/DispDateRange' from origin 'http://172.18.129.236' has been blocked by CORS policy: 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.middleware.cors.CORSMiddleware の設定を加えることで解消。
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() # origins = ["http://localhost", # "http://localhost:8080" ] app.add_middleware(CORSMiddleware, allow_origins=["*"], #allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"] ) @app.get("/api/newbuild/DispDateRange") async def disp_date_range(): return ["2024-03-31","2024-04-14"]
fetch() for javascript 側にも、{mode:"cors"} を必要とする情報も 見かけましたが、私の環境ではこれがなくても問題なく動作しました。
let res = await fetch(req_url,{mode: "cors"});