LoginSignup
0
1

More than 1 year has passed since last update.

【入門】DjangoRestFrameworkとReactHooksでHello world表示

Last updated at Posted at 2022-09-03

はじめに

タイトルの通り、バックエンドにDjangoRestFramework、フロントエンドにReactHooksを採用してブラウザに「Hello world」を表示するだけのアプリを作ったのでアウトプットします。

環境

  • Windows10
  • Python 3.10.2
  • Django==4.1
  • djangorestframework==3.13.1
  • django-cors-headers==3.13.0

バックエンド

1. 環境構築

作業ディレクトリを作成して仮想環境を作成します。
$ mkdir backend
$ cd backend
$ python -m venv myvenv
$ myvenv\Scripts\activate

必要なライブラリをインストールします

(myvenv) pip install django
(myvenv) pip install djangorestframework
(myvenv) pip install django-cors-headers

プロジェクトとアプリを作成します

(myvenv) django-admin startproject project .
(myvenv) django-admin startapp app

2. settings.py

INSTALLED_APPSに以下の3つを追加
settings.py
INSTALLED_APPS = [
    'rest_framework',
    'corsheaders',
    'app',
]

MIDDLEWAREに以下を追加

settings.py
MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',
]

CORS_ORIGIN_WHITELIST追加

settings.py
CORS_ORIGIN_WHITELIST = (
    'http://localhost:3000',
)

2. views.py

以下のサイトのFunction Based Viewsを引用させてもらいました。

views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view()
def hello_world(request):
    return Response({"message": "Hello, world!"})

3. 動作確認

http://127.0.0.1:8000/app/hello_world

にアクセスすると{message:Hello world1}が取得できることがわかります。
image.png

フロントエンド

1. 環境構築

npx create-react-app [プロジェクト名]でプロジェクトフォルダを作成します。

$ npx create-react-app frontend

今回は以下のファイルを編集します

  • src/App.js
  • src/components/ApiFetch.js(新規作成)

2. ApiFetch.js(新規作成)

ApiFetch.js
import React from 'react'
import { useEffect } from 'react';
import { useState } from 'react'

const ApiFetch = () => {
    const initialState = {"message": ""};
    const [message, setMessage] = useState(initialState);
    useEffect(()=>{
        fetch("http://127.0.0.1:8000/app/hello_world", {method: "GET"})
        .then(res=>res.json())
        .then(data => {setMessage(data)});
    }, [])
    return (
    <div>
            {message.message}
    </div>
  )
}

export default ApiFetch

3. App.js

App.js
import './App.css';
import ApiFetch from './components/ApiFetch';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <ApiFetch />
      </header>
    </div>
  );
}

export default App;

動作確認

http://localhost:3000/にアクセス
image.png

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1