-
fetch API 사용 시 headers가 비어있는 문제et cetera/Trouble Shooting 2021. 6. 11. 18:46반응형
■ 상황
장바구니 미션에서, fetch API를 사용해서 장바구니에 상품을 추가했다.
상품을 추가하고나면 cart_id가 response headers의 location에 담겨서 날아오게끔 API가 구현되어 있었다.
그래서 response를 그대로 console.log 찍어봤는데, headers 안에 아무것도 들어있지 않았다.
하지만 다른 크루들의 결과물을 보니, axios의 response headers에는 원하는 값이 담겨져 있었다.
fetch(API_URL.CART, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ product_id: product.product_id, }), }) .then((response) => { if (!response.ok) { throw new Error(ERROR_MESSAGE.FAILED_TO_ADD_TO_CART); } console.log(response.headers); // undefined }
■ 상세
fetch API의 Headers 클래스 인스턴스가 iterable object를 반환하기 때문에 생기는 문제였다.
axios는 plain object를 반환하기 때문에 그냥 원하는 값을 바로 가져올 수 있었던 거고.
fetch API를 통해서 가져오는 iterable object의 데이터인 Headers나 URLSearchParams 같은 데이터들은
브라우저의 콘솔로는 바로 확인하는 것이 불가능하다.
console.log를 사용하려고 하더라도, 순회를 통해 값을 출력해야한다.
fetch(API_URL.CART, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ product_id: product.product_id, }), }) .then((response) => { if (!response.ok) { throw new Error(ERROR_MESSAGE.FAILED_TO_ADD_TO_CART); } // 요렇게 forEach를 사용해서 출력하거나 response.headers.forEach(console.log); // 요렇게 for..of를 사용해서 출력할 수 있다고 합니당 for(let entry of response.headers.entries()) { console.log(entry); } }
굳이 순회하지 않고 원하는 값만 가져오고 싶다면, 다음과 같이 Headers 객체의 메소드를 사용할 수 있다.
const responseLocation = response.headers.get('location'); const cartId = responseLocation.slice(responseLocation.lastIndexOf('/') + 1);
■ 느낀 점
뭔가 필요성을 느끼기 전까지는 라이브러리를 도입하는 데에 좀 보수적인 편인데,
그래서인지 이때까지는 axios보다는 그냥 fetch를 사용하는 편이었다.
하지만, 최근 들어 axios를 사용하면 딱히 겪지 않아도 될 사소한 불편함들이 하나둘씩 느껴지기 시작했다.
JSON 데이터로 자동 변환해주는 것도 생각보다 편한 것 같고. (자꾸 중간중간에 까먹는다..)
이 Headers 문제도, 알고 있었다면 별 문제가 아니었겠지만.. 원인을 알 수가 없어서 시간을 많이 날렸다.
다음부터는 axios의 사용을 적극적으로 고려해볼 듯.
■ 참고
Missing headers in Fetch response
I need to make a CORS post request. I need to use fetch because axios's response is already processed to json. But in fetch response, the headers is empty. But I don't think this is the server pr...
stackoverflow.com
Headers - Web APIs | MDN
The Headers interface of the Fetch API allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing headers from the list of the request's headers.
developer.mozilla.org
반응형'et cetera > Trouble Shooting' 카테고리의 다른 글
Parcel의 Cannot find module './style.module.scss' or its corresponding type declarations. 에러 (2) 2022.01.17 click 이벤트보다 blur 이벤트가 먼저 발생하는 문제 (0) 2021.12.24 모바일에서 Webpack-dev-server에 접근하지 못하는 문제 (0) 2021.09.30 Webpack cli가 종료되지 않는 문제 (4) 2021.09.24 Uncaught SyntaxError: Unexpected token < in JSON at position 0 (0) 2021.04.24