[Full-stack] Django and React.js 整合
Published in
3 min readMay 5, 2020
主要是針對django 和 React 結合所需要的設定步驟紀錄
- 建立環境並啟動它
$ virtualenv env
$ source env/bin/activate
(env)$
2. 安裝django套件
$ pip install django==2
$ pip install django-cors-headers
3. 建立 django project 和 django application
$ django-admin startproject django_react
$ cd django_react
$ python manage.py startapp backend
4. 編輯 django project 內的檔案
settings.py
# settings.pyINSTALLED_APPS = [
...
...
'backend',
]MIDDLEWARE = [
...
...
'corsheaders.middleware.CorsMiddleware',
]TEMPLATES = [
{
...
'DIRS': ['frontend/build'],
...
},
]STATICFILES_DIRS = [
os.path.join(BASE_DIR, "frontend/build/static"),
]CORS_ORIGIN_ALLOW_ALL = True
urls.py
# urls.py
from django.views.generic import TemplateViewurlpatterns = [
path('admin/', admin.site.urls),
path('', TemplateView.as_view(template_name='index.html')),
]
5. 建立 React project ( https://reactjs.org/docs/create-a-new-react-app.html)
$ npx create-react-app frontend
$ cd frontend
$ npm run build
6. 執行 django 專案
$ python manage.py runserver
7. 查看網址,會發現到 http://localhost:8000/ 網頁會被導入到 React頁面
如果你覺得文章很棒或有幫助到您,不妨幫我點個拍手吧! 謝謝…