2025.03.08(更新日: 2025.03.08)
【フロントエンドとの連携】CORS設定でフロントエンドからAPIを呼び出せるようにする
はじめに
現状、Django REST frameworkで、タスクアプリのバックエンドが構築されている。
現状のタスク管理アプリで出来ること
タスクの一覧表示、新規登録、詳細表示、更新、削除。
詳しくはDjango REST Framework(DRF)のルーティングがどのように機能しているかを深掘りし、urls.pyの仕組みを完全理解する | ki-hi-ro.com > 一覧取得を参照していただきたい。
これからやりたいこと
ReactまたはVue.jsを使用して、フロントエンドと連携していきたい。
最初のステップ
まずは、CORS設定というものを行い、フロントエンドからAPIを呼び出せるようにする必要がある。
CORS設定とは
Cross-Origin Resource Shareing、クロスオリジンリソース共有は、異なるオリジン(ドメインやポートが異なるサイト)同士でリソースをやり取りするための仕組み。
デフォルトでは、ブラウザは異なるオリジン間の通信をブロックする。
Django REST framework(バックエンド)とReactやVue(フロントエンド)を連携する場合、通常は異なるオリジンになる。
環境 | URL |
DRF | http://127.0.0.1:8000/ |
React | http://localhost:3000/ |
CORS設定を有効にしないと、フロントエンドからバックエンドにアクセスできない。
DjangoでCROS設定を有効にするには
django-cors-headersというパッケージを使用する。pipでインストール。
(venv) Mac:django_todo shibatahiroshitaka$ pip install django-cors-headers
Collecting django-cors-headers
Downloading django_cors_headers-4.4.0-py3-none-any.whl (12 kB)
Requirement already satisfied: django>=3.2 in /Users/shibatahiroshitaka/Downloads/python/venv/lib/python3.8/site-packages (from django-cors-headers) (4.2.19)
Requirement already satisfied: asgiref>=3.6 in /Users/shibatahiroshitaka/Downloads/python/venv/lib/python3.8/site-packages (from django-cors-headers) (3.8.1)
Requirement already satisfied: sqlparse>=0.3.1 in /Users/shibatahiroshitaka/Downloads/python/venv/lib/python3.8/site-packages (from django>=3.2->django-cors-headers) (0.5.3)
Requirement already satisfied: backports.zoneinfo; python_version < "3.9" in /Users/shibatahiroshitaka/Downloads/python/venv/lib/python3.8/site-packages (from django>=3.2->django-cors-headers) (0.2.1)
Requirement already satisfied: typing-extensions>=4; python_version < "3.11" in /Users/shibatahiroshitaka/Downloads/python/venv/lib/python3.8/site-packages (from asgiref>=3.6->django-cors-headers) (4.12.2)
Installing collected packages: django-cors-headers
Successfully installed django-cors-headers-4.4.0
WARNING: You are using pip version 20.2.3; however, version 25.0.1 is available.
You should consider upgrading via the '/Users/shibatahiroshitaka/Downloads/python/venv/bin/python3 -m pip install --upgrade pip' command.
setting.py(django_todo/django_todo/settings.py)にCROS設定を追加する。
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'myapp',
'corsheaders'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware'
]
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000" # Reactの場合
]
今回はReactを使用しようと思うので、CORS_ALLOWED_ORIGINSにはReactのオリジンを設定した。
コミット完了
CORS設定 · ki-hi-ro/django_todo@c17a829に今回の内容をコミットした。
(venv) Mac:django_todo shibatahiroshitaka$ git status
On branch master
Your branch is up to date with 'origin/master'.
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git restore <file>..." to discard changes in working directory)
modified: django_todo/settings.py
no changes added to commit (use "git add" and/or "git commit -a")
(venv) Mac:django_todo shibatahiroshitaka$ git add .
(venv) Mac:django_todo shibatahiroshitaka$ git commit -m "CORS設定"
[master c17a829] CORS設定
1 file changed, 7 insertions(+), 1 deletion(-)
(venv) Mac:django_todo shibatahiroshitaka$ git push origin master
Enumerating objects: 7, done.
Counting objects: 100% (7/7), done.
Delta compression using up to 8 threads
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 478 bytes | 478.00 KiB/s, done.
Total 4 (delta 3), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (3/3), completed with 3 local objects.
To https://github.com/ki-hi-ro/django_todo.git
1785315..c17a829 master -> master
投稿ID : 28976
コメントを残す