django rest framework - CORS

nikevapormax·2022년 6월 28일
0

TIL

목록 보기
60/116

django rest framework - CORS

CORS를 위한 세팅

  1. 터미널에서 아래 명령어 입력
$ python -m pip install django-cors-headers
  1. settings.py 세팅
  • INSTALLED_APP
INSTALLED_APPS = (
    ...
    'corsheaders',
    ...
)
  • MIDDLEWARE
MIDDLEWARE = [
    ...,
    'corsheaders.middleware.CorsMiddleware',
    ...,
]
  • 맨 아래에 추가
CORS_ALLOWED_ORIGINS = [
    'http://127.0.0.1:5500',
]

live server 결과

  • 처음에는 계속 아래의 연결이 되지 않았다는 에러가 나왔다.
  • 위의 세팅을 진행하고 아직 Unauthorized이지만 CORS는 통과한 것을 볼 수 있었다.
  • 터미널 창을 보며 디버깅을 하였다. 내용은 슬래시가 빠져있네 들어있네이러면서 별다른 해결책을 제시하는 것은 아니었다.그러다가 415 에러를 만나게 되었다.
  • 아래와 같이 코드를 작성해 해결하였다.
    • headers에 추가한 코드를 보면 된다.
async function handleSignup() {
    const signupData = {
        username: document.getElementById("floatingInput").value,
        password: document.getElementById("floatingPassword").value,
        email: document.getElementById("floatingInputEmail").value,
        fullname: document.getElementById("floatingInputFullname").value,
    }

    const response = await fetch(`http://127.0.0.1:8000/user/`, {
        headers: {
            Accept: "application/json",
            'Content-type': 'application/json'
        },
        method: "POST",
        body: JSON.stringify(signupData)
    })

    response_json = await response.json()

    if (response.status == 200) {
        window.location.replace(`http://127.0.0.1:5500/login.html`)
    } else {
        alert(response.status)
    }
}

async function handleLogin() {
    const loginData = {
        username: document.getElementById("floatingInput").value,
        password: document.getElementById("floatingPassword").value,
    }

    const response = await fetch(`http://127.0.0.1:8000/user/api/token/`, {
        headers: {
            Accept: "application/json",
            'Content-type': 'application/json'
        },
        method: "POST",
        body: JSON.stringify(loginData)
    })

    response_json = await response.json()
    console.log(response_json.access)

    if (response.status == 200) {
        localStorage.setItem("access", response_json.access);
        localStorage.setItem("refresh", response_json.refresh);

        const base64Url = response_json.access.split('.')[1];
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        const jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) {
            return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));

        localStorage.setItem("payload", jsonPayload);
        // window.location.replace(`http://127.0.0.1:5500/index.html`)
    } else {
        alert(response.status)
    }
}
profile
https://github.com/nikevapormax

0개의 댓글