jayeon front 개발 [SveltKit]

최준호·2023년 5월 8일

FastAPI

목록 보기
1/9
post-thumbnail

📗 SvelteKit

📄 프로젝트 생성

Svelte 공식 사이트를 참고하여 진행했다.

npm create svelte@latest front

front 프로젝트를 jayeon 폴더내에서 생성한다.

✅ 프로젝트 시작

npm install
npm run dev

✅ api 통신하기

<script>
    let test = ''

    function get_test() {
        fetch("http://127.0.0.1:8000/v1/test").then((res) => {
            res.json().then((json) => {
                test = json.message;
            });
        });
    }
  
    get_test();
</script>

<h1>{test}</h1>

front/src/routes/test/+page.svelte
파일을 생성하여 다음과 같이 작성한다.

그럼 다음과 같이 cors 에러가 나고 있다!... 해당 부분을 수정해보자

✅ api 수정

from fastapi import FastAPI
from starlette.middleware.cors import CORSMiddleware

from domain.test import test_router

app = FastAPI()

origins = [
    "http://localhost:5173"
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

app.include_router(test_router.router)

이전 코드를 다음과 같이 cors 에러가 나지 않도록 설정해준다.

그러면

cors가 나지 않고 정상적으로 데이터를 가져오는 것을 확인할 수 있다!

0개의 댓글