ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Django] REST API (4) - Frontend 연동
    Phthon/Django 2020. 1. 1. 14:21
    728x90

    1. React 앱 작성

    npm을 사용하기 위햐서는 Node.js 설치가 필요

     

    https://nodejs.org/en/download/

     

    Download | Node.js

    Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

    nodejs.org

    # prompt
    
    npm -v //설치 확인
    
    npm install -g yarn //yarn 설치
    yarn --version //yarn 설치 확인
    
    npm install -g create-react-app //react app을 만들어주는 패키지 설치
    
    //cd로 작업할 디렉토리로 이동후
    create-react-app frontend //react app 생성
    
    cd frontend
    yarn start //정상 실행되는지 테스트
    // frontend/src/App.js
    
    import React, { Component } from 'react';
    
    class App extends Component {
        state = {
            posts: []
        };
    
        async componentDidMount() {
            try {
                const res = await fetch('http://127.0.0.1:8000/posts');
                const posts = await res.json();
                this.setState({
                    posts
                });
            } catch (e) {
                console.log(e);
            }
        }
    
        render() {
            return (
                <div>
                    {this.state.posts.map(item => (
                        <div key={item.id}>
                            <h1>{item.title}</h1>
                            <span>{item.content}</span>
                        </div>
                    ))}
                </div>
            );
        }
    }
    
    export default App;
    

     

    2. HTTP 접근제어 규약(CORS : Cross-Origin Resource Sharing) 추가

     

    pip install django-cors-headers

    # restStudy/settings.py
    
    INSTALLED_APPS = [
        'rest_framework', # REST API 패키지
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'main',
        'restful',
        'corsheaders', # CORS 패키지 <- 추가
    ]
    
    ...
    
    MIDDLEWARE = [
        'corsheaders.middleware.CorsMiddleware',     # CORS 패키지 <- 추가
        'django.middleware.common.CommonMiddleware',
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ]
    
    ...
    
    CORS_ORIGIN_ALLOW_ALL = True
    
    CORS_ALLOW_CREDENTIALS = True
    
    CORS_ORIGIN_WHITELIST = [
        'http://localhost:3000',
    ]

     

    3. 서버 실행

     

    728x90
Designed by Tistory.