はじめに
今回、会社の研修でFastAPIとSvelteで環境構築を行うことがあったので、備忘録として残していきたいと思います。
前提
fastAPIのバージョン 0.111.0
Svelteのバージョン   4.2.7
OS MacOS
『クロスオリジン』とは
クロスオリジンとは特定のドメインからの通信を許可する設定になります。
この設定を行うことでFastAPI側とSvelte側の通信が可能となります。
FastAPI側の設定
① .envファイルを作成して設定を変更
from fastapi.middleware.cors import CORSMiddleware でCORSMiddleware をインポート
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
    'http://localhost:5173', 
]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=['*'],
    allow_headers=['*']
)
この部分に許可するオリジン(今回はSvelte側のサーバーのURL)を追加
origins = [
    'http://localhost:5173', #ここにSvelte側のサーバーのURLを設定
]
②APIを返す処理を書く
今回はsample.pyというファイルを作成し、APIを返す処理を書いていきます
from fastapi import FastAPI
app = FastAPI()
# @app.get("/api")に変更
@app.get("/api")
async def root():
    return {"message": "Hello World"}
Svelte側の設定
①svelte.config.jsの設定を変更
import adapter from '@sveltejs/adapter-auto';
/** @type {import('@sveltejs/kit').Config} */
const config = {
	kit: {
		// adapter-auto only supports some environments, see https://kit.svelte.dev/docs/adapter-auto for a list.
		// If your environment is not supported, or you settled on a specific environment, switch out the adapter.
		// See https://kit.svelte.dev/docs/adapters for more information about adapters.
		
		adapter: adapter({
            // default options are shown. On some platforms
            // these options are set automatically — see below
            
            // ここを追加
            pages: '../server/static',
            assets: '../server/static',
            fallback: 'index.html',
            precompress: false,
            strict: true
        })
	}
};
export default config;
②vite.config.jsにプロキシの設定を追記
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
export default defineConfig({
	plugins: [sveltekit()],
	server: {
	// ここを追加
		proxy: {
				'/api': {  // ここにはsample.pyに書いたルーティングを書く
				'target': env.VITE_API_BASE_URL
				changeOrigin: true,
			}
		}
	}
});
.envファイルの設定
フロントエンドのプロジェクトの直下に.envというファイルを作成して以下を追記します。
// ここを追記
VITE_API_BASE_URL='fastAPI側のポート'
動作確認
①ボタンを押してVITE_API_BASE_URL='fastAPI側のポート'で設定したAPIを叩く
<script>
	import { onMount } from 'svelte';
	import Counter from './Counter.svelte';
 
    async function fetchData() {
		console.log('おした');
		try {
			const response = await fetch(`/api`);
			if (response.ok) {
				console.log(`/api`);
				const data = await response.json();
				console.log(data);
			}
		} catch (e) {
			console.error('Failed to fetch data:', e);
		}
	}
 </script>
 <section>
	<button on:click={fetchData}>CORSチェック</button>
</section>
『CORSチェック』ボタンを押してみてブラウザのコンソールにこのように表示されればOKです!!

まとめ
いかがでしたでしょうか??
今回の設定ができていれば、フロントエンド側とバックエンド側の連携はバッチリです!
間違いなどありましたら教えてくださると幸いでございます。
それでは〜!!
