frontend 연결하기
투표 앱 프로젝트에 “django-cors-headers” 종속성 추가
uv add django-cors-headers
settings.py 수정
- INSTALLED_APPS에 'corsheaders' 추가
- MIDDLEWARE에 'corsheaders.middleware.CorsMiddleware’ 추가

요청을 허용할 origin을 선택, 허용할 메소드와 헤더도 추가
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
"http://127.0.0.1:3000",
]
CSRF_TRUSTED_ORIGINS = [
"http://localhost:3000",
"http://127.0.0.1:3000",
]
# 허용할 메소드와 헤더
CORS_ALLOW_METHODS = (
"DELETE",
"GET",
"OPTIONS",
"PATCH",
"POST",
"PUT",
)
CORS_ALLOW_HEADERS = (
"accept",
"authorization",
"content-type",
"user-agent",
"x-csrftoken",
"x-requested-with",
)

터미널 열고 frontend 프로젝트 git clone
$ git clone https://github.com/gotoweb/poll-frontend-v0.git
터미널에서 frontend 서버 빌드하고 실행
$ cd poll-frontend-v0
$ npm install # npm 설치되어 있지 않으면 설치
$ npm run build
$ npm run dev

backend 서버도 실행
$ source .venv/bin/activate
$ python manage.py runserver

fronend - backend 요청 과정
“http://localhost:3000/polls/1”으로 접속하면, frontend 서버로 GET 요청을 보내고 html을 응답 받음


“네”를 선택하고 투표하면

“http://localhost:8000/polls/1/vote/”(backend 서버)으로 POST 요청을 보냄

POST 요청에 대한 payload는 선택한 항목의 id

이어서 “http://localhost:8000/polls/1/results/”으로 POST 요청을 보내고

투표 결과에 대한 json 데이터를 응답 받음

'Language > Python' 카테고리의 다른 글
[Python] Django 투표 앱 RESTful api로 리팩토링하기 (0) | 2024.12.17 |
---|---|
[Python] Django Model, View 사용하기 (0) | 2024.12.17 |
[Python] Django 투표 앱 만들기 (2) (0) | 2024.12.17 |
[Python] Django 투표 앱 만들기 (1) (1) | 2024.12.17 |
[Python] Django 프로젝트 생성하기 (1) | 2024.12.17 |