티스토리 뷰

WEB/Django

장고와 리액트 연결하기

취뽀가자!! 2019. 1. 9. 15:20

장고와 리액트를 연결하기 위한 순서는 다음과 같다.


1. 장고를 위한 proxy를 만들기

2. djnago-cors-headers 설치

3. corsheaders를 INSTALLED_APPS에 추가

4. corsheaders.middleware.CorsMiddleware를 django.middleware.common.CommonMiddleware전에 추가

5. CORS_ORIGIN_ALLOW_ALL = True를 base.py 맨 아래 추가

6. 장고가 bundle을 static file로 로딩하게 해야 한다.

7. 디렉토리 전체를 위한 views.py추가


proxy

yarn build를 할 때마다 build디렉토러에 개발한 내용들이 압축될 것이다. 이걸 장고가 읽을 수 있도록 해야 한다. 리액트가 실행되고 있는 포트 3천에서 장고가 실행되고 있는 포트 8천에 있는 api를 불러오기 위해서는 proxy작업을 해 줘야 한다.

{
"name": "frontend",
"version": "0.1.0",
"private": true,
"proxy" : "http://127.0.0.1:8000",
"dependencies": {
"node-sass": "^4.11.0",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"react-scripts": "2.1.3",
"sass-loader": "^7.1.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}


django-cors-headers

먼저 설치를 해 준다.

pip install django-cors-headers


그 다음 INSTALLED_APPS에 corsheaders를 추가해 준다.

THIRD_PARTY_APPS = [
'allauth',
'allauth.account',
'allauth.socialaccount',
'allauth.socialaccount.providers.facebook',
'rest_framework',
'rest_framework.authtoken',
'taggit',
'taggit_serializer',
'rest_auth',
'rest_auth.registration',
'corsheaders'
]


그리고 middleware에 CorsMiddleware을 추가해 준다.

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]


CORS_ORIGIN_ALLOW_ALL = True도 맨 아래에 추가해준다.


Static files

이제, 장고가 번들을 static file로 로딩하게 해야한다.

우리의 statics file은 웹팩이 만들어준 파일을 의미해. 즉, 이는 build 안에 위치해야 한다.

따라서 장고에게 우리의 static 파일들은 프론트엔들 빌드에도 있다고 알려줘야해.

str(ROOT_DIR.path('frontend', 'build', 'static')),추가


STATICFILES_DIRS = [
str(APPS_DIR.path('static')),
str(ROOT_DIR.path('frontend', 'build', 'static')),
]


view

디렉터리 전체를 위한 views.py를 생성해 준다. 그리고 아래 코드를 추가해 준다.
from django.views.generic import View
from django.http import HttpResponse
from django.conf import settings
import os


class ReactAppView(View):
def get(self, request):
try:
with open(os.path.join(str(settings.ROOT_DIR), 'frontend', 'build', 'index.html')) as file:
return HttpResponse(file.read())
except:
return HttpResponse(
"""
index.html not found ! build your React app !!
""",
status=501,
)

위 코드는 request를 받을때마다 루트 디렉터리 -> frontend -> build 안에서 index.html파일을 열려고 할 것이다.


이제 장고 서버에서 확인해보면 리액트 앱에서 개발했던 모습들을 볼 수 있을 것이다.



'WEB > Django' 카테고리의 다른 글

Login in with Facebook  (0) 2019.01.07
로그인/로그아웃/회원가입 기능 구현  (0) 2019.01.07
JWT(Json Web Token)  (0) 2019.01.07
The Request Object in Django  (0) 2018.12.25
Hidden Model Fields in Django  (0) 2018.12.24
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함