TypeScript - fetch headers 설정

이종호·2021년 8월 8일
2

TypeScript

목록 보기
6/7
post-thumbnail

TL;DR(code)

// HeadersInit타입의 객체 생성
const requestHeaders: HeadersInit = new Headers(); 

// set() 통해 key, value 추가
requestHeaders.set('Content-Type', 'application/json'); 
requestHeaders.set(
  'Authorization',
  localStorage
  ?.getItem('token')
  ?.slice(1, localStorage.getItem('token')!.length - 1) || 'no token');

// 실제 fetch메소드에 적용
fetch('url..', { headers: requestHeaders });

fetch headers 설정

const requestHeaders: HeadersInit = new Headers();
  requestHeaders.set('Content-Type', 'application/json');
  requestHeaders.set(
    'Authorization',
    localStorage
      ?.getItem('token')
      ?.slice(1, localStorage.getItem('token')!.length - 1) || 'no token'
  );


fetch('http://18.116.64.187:8000/carts', {
        method: 'POST',
        headers: requestHeaders,
        body: JSON.stringify({
          products: [...productEntitiy, { product_id: id, count: count }],
        }),
})
  .then(res => res.json())
  .then(data => {
  console.log('detail');
  console.log(data);
});
  • requestHeader에 타입은 HeaderInit형으로 만들어야 한다.
  • 실제 구현은 new Headers()로 가능하다.
  • set()으로 값을 넣을 수 있다.

headersHeadersInit타입을 가지고있다



HeadersInitHeaders, string[][], Recode<string, string>형태를 가질 수 있다.


Headers

  • interface를 통해 사용 가능한 메소드들을 볼 수 있다.
  • new 를 통해 생성할 수 있다.
/** This Fetch API interface allows you to perform various actions on HTTP request and response headers. These actions include retrieving, setting, adding to, and removing. A Headers object has an associated header list, which is initially empty and consists of zero or more name and value pairs.  You can add to this using methods like append() (see Examples.) In all methods of this interface, header names are matched by case-insensitive byte sequence. */
interface Headers {
    append(name: string, value: string): void;
    delete(name: string): void;
    get(name: string): string | null;
    has(name: string): boolean;
    set(name: string, value: string): void; // 우리가 사용한 메서드!!!!!!
    forEach(callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: any): void;
}

declare var Headers: {
    prototype: Headers;
    new(init?: HeadersInit): Headers;
};

주석을 해석한 글
이 Fetch API 인터페이스를 사용하면 HTTP 요청 및 응답 헤더에 대해 다양한 작업을 수행할 수 있습니다. 이러한 작업에는 검색, 설정, 추가 및 제거가 포함됩니다. 헤더 개체에는 처음에는 비어 있고 0개 이상의 이름과 값 쌍으로 구성된 연결된 헤더 목록이 있습니다. adpend()와 같은 메서드를 사용하여 이 메서드에 추가할 수 있습니다(예제 참조). 이 인터페이스의 모든 메서드에서 헤더 이름은 대소문자를 구분하지 않는 바이트 시퀀스로 일치합니다.


그래서 이런 식으로 set메소드를 통해 값을 키 값 형태로 지정할 수 있다.

느낀 점

  • 먼저 stackoverflow에서 답을 찾았다.
  • 실제 맞는지 vscode에서 ts doc을 찾았다.
  • 일단 어느정도 맞는 것 같다.
profile
코딩은 해봐야 아는 것

0개의 댓글