코딩한걸음
728x90
반응형
💡
이 포스팅은 window, vscode 기준으로 작성되었습니다.

루트폴더 만들고 html과 js 만들기

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>프론트엔드</title>
    <script src="index.js"></script>
</head>
<body>
    <h1>프론트엔드</h1>
</body>
</html>

// index.js
console.log("자바스크립트 불러오기")

vscode의 확장 프로그램인 live server 를 실행하고

f12를 누르고 콘솔을 선택하면 다음과 같이 뜬다

// index.js
console.log("자바스크립트 불러오기")

window.onload = async function loadArticles(){
    const response = await fetch('http://127.0.0.1:8000/articles/',{method:'GET'})

    response_json = await response.json()

    console.log(response_json)
}

live server의 포트는 5500번이고 우리가 돌리는 서버의 포트는 8000번이기 때문에

포트가 달라서 뜨는 오류이다.

CORS에서 포트를 허용해주면 접근가능해진다.

CORS 허용하기

## console
pip install django-cors-headers
pip freeze > requirements.txt

## drf_project/settings.py
INSTALLED_APPS = [
    ...,
    "corsheaders",
    ...,
]

## drf_project/settings.py
MIDDLEWARE = [
    ...,
    "corsheaders.middleware.CorsMiddleware",
    "django.middleware.common.CommonMiddleware",
    ...,
]

CORS_ALLOW_ALL_ORIGINS = True

‘corsheaders.middleware.CorsMiddleware’ 이부분의 위치가 중요한데

그냥 최상단에 두면 편하다

CORS를 허용해주니 데이터를 잘 받아온다

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>프론트엔드</title>
    <script src="index.js"></script>
</head>
<body>
    <h1>프론트엔드</h1>
    <div id="articles">

    </div>
</body>
</html>

<div id="articles">를 추가하고 js에서 해당 id를 찾아 요소를 추가해준다

// index.js
window.onload = async function loadArticles(){
    const response = await fetch('http://127.0.0.1:8000/articles/',{method:'GET'})

    response_json = await response.json()

    const articles = document.getElementById("articles")

    response_json.forEach(element => {
        const newArticle = document.createElement("div")
        newArticle.innerText = element.title
        articles.appendChild(newArticle)
    })
}


Uploaded by N2T

728x90
반응형
profile

코딩한걸음

@Joonyeol_Yoon

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!