관리 메뉴

Silver Library (Archived)

[react] 요즘 fetch Auth 구성에 대한 고찰. 본문

Face the fear, build the future/Revision Sector

[react] 요즘 fetch Auth 구성에 대한 고찰.

Chesed Kim 2022. 12. 4. 10:14
반응형

코드를 계속 보다보니 느껴진 게, 대체 저건 뭘까? 였습니다.

언제부턴가 TS 와 비슷해지려는 느낌이 보이는 JS 코드들이 보이는데, 역시 2018년을 기점으로 권고안이 달라진 것을 볼 수가 있었습니다 (미국 내 쿠키정책).

 

그리고 이것의 정체가 바로 CORS policy 인데요. 이에 대해 지속적으로 알아보고자 합니다.

 

아래는 client 측을 기준으로 재구성 한 예시 코드입니다.

const loginButtonAsKim = document.getElementById("loginAuthKim")
const loginButtonAsRaynor = document.getElementById("loginAuthRaynor")
const adminButton = document.getElementById("admin")
const responsesDiv = document.getElementById("responses")

loginButtonAsKim.addEventListener("click", () => {
	login("Kim")
})

loginButtonAsRaynor.addEventListener("click", () => {
	login("Raynor")
})

adminButton.addEventListener("click", () => {
	fetch("http://localhost:3000/adminData", {
    	credentials: "include",
        headers: {
        	"Content-Type": "application/json",
        },
    })
    	.then(res => res.text())
        .then(data => (responsesDiv.textContent = data))
})

function login(username) {
	fetch("http://localhost:3000/login", {
    	method: "POST",
        credentials: "include",
        headers: {
        	"Content-Type": "application/json",
        },
        body: JSON.stringify({ username }),
    })
    	.then(res => res.text())
        .then(data => (responsesDiv.textContent = data))
}

그렇다면 axios 할 때도 이렇게 작성을 해줘야 정상적으로 작동하지 않을까 하는 생각입니다.

 

Ref.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type

 

Content-Type - HTTP | MDN

The Content-Type representation header is used to indicate the original media type of the resource (prior to any content encoding applied for sending).

developer.mozilla.org

https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fetch

 

Fetch 사용하기 - Web API | MDN

Fetch API는 HTTP 파이프라인을 구성하는 요청과 응답 등의 요소를 JavaScript에서 접근하고 조작할 수 있는 인터페이스를 제공합니다. Fetch API가 제공하는 전역 fetch() (en-US) 메서드로 네트워크의 리소

developer.mozilla.org