I learned

내일배움캠프 AI - TIL 45

이모냥냥 2022. 11. 6. 19:48
반응형
❤️‍🔥TIL : Today I Learned❤️‍🔥
그날그날 내가 공부한 것을 정리하는 것

 

 

 

내일배움캠프 AI트랙 45day

 

오늘 배운 내용

django와 Front-end 연결하기 - Fetch

JS로 Backend와 연결하는 방법에는 크게 ajax와 fetch가 있다. ajax는 익숙하므로 fetch를 사용해서 통신을 해보았다.

Fetch API는 HTTP 파이프라인을 구성하는 요청과 응답 등의 요소를 JavaScript에서 접근하고 조작할 수 있는 인터페이스를 제공한다.

 

fetch 명세는 jQuery.ajax()와 크게 두 가지에서 다르다

  • fetch()가 반환하는 프로미스 객체는 404, 500과 같은 HTTP 오류 상태를 수신해도 거부되지 않는다. 
  • fetch()의 프로미스는 서버에서 헤더를 포함한 응답을 받는 순간 정상적으로 이행한다. 대신, 응답의 상태가 200-299를 벗어날 경우 ok (en-US) 속성이 false로 설정된다. 프로미스가 거부되는 경우는 네트워크 연결이 실패하는 경우를 포함, 아예 요청을 완료하지 못한 경우로 한정된다.
document.addEventListener("DOMContentLoaded", function(){
    handleMock()
});
async function handleMock(){
    const response = await fetch('http://127.0.0.1:8000/musics/recommend/',{
        headers: {
            "Authorization":"Bearer " + localStorage.getItem("access")
        },
        method:'GET',
    })
    
    const response_json = await response.json()
    console.log(response_json)
}

 

데이터 전달방법 01 : JSON

async function handleMock(){
    const response = await fetch('http://127.0.0.1:8000/musics/',{
        headers: {
        	"Content-Type":"application/json",
            "Authorization":"Bearer " + localStorage.getItem("access"),
        },
        method:'POST',
        body: JSON.stringify({
             "content":"username",
             "grade":"5"
        }),
    })
    const response_json = await response.json()
}

 

데이터 전달방법 02 : FormData

async function handleUpdate() {
    let fullname = document.getElementById("fullname").value;
    let email = document.getElementById("email").value;
    let fileField = document.querySelector('input[type="file"]').files[0];
    
    const profile_formData = new FormData();
    profile_formData.append("fullname",fullname);
    profile_formData.append("email",email);
    if (fileField!=undefined){
        profile_formData.append("profile_image", fileField);
    }
    

   const response = await fetch('http://127.0.0.1:8000/users/profile/', {
        headers: {
             "Authorization":"Bearer " + localStorage.getItem("access")
        },
        method: 'PUT',
        body: profile_formData,
    })
    .then(response => {
        if(!response.ok){
            throw new Error(`${response.status} 에러가 발생했습니다.`);    
        }
        return response.json()
    }).then(result => {
        alert("프로필이 수정되었습니다.")
        document.getElementById("profile_img").setAttribute("src","http://127.0.0.1:8000"+result['profile_image'])
    }).catch(error => {
        alert("프로필 수정에 실패하였습니다.\n자세한 내용은 관리자에게 문의해주세요.")
        console.warn(error.message)
    });
}
반응형