TIL - fetch () get/post

Minsoo·2021년 12월 20일
0

TIL

목록 보기
7/8
post-thumbnail

1.부트캠프 자체 JSON파일을fetch()api를 사용해 간단한 채팅앱을 만들어 보았다.
I'm

2. AJAX

(Asynchronous JavaScript And XML, 비동기적 JavaScript와 XML) - AJAX는 서버에서 추가 정보를 비동기적으로 가져올 수 있게 해주는 포괄적인 기술

AJAX
Asynchronous Javascript And XML
AJAX requests are asynchronous HTTP requests which happen after page load.
Example: Google search (autocomplete)

3. fetch() syntax

fetch(url, [options])

  • "get"request by default
  • options – , method나 header 등을 지정
  • stringify는 매개변수를 json형식으로 변환해줌
    example
 { author: yourName.value, content: yourMessage.value }

이것을

 { "author": ~, "content": ~}

이렇게 변환한다.

get request

fetch(URL)
  .then(response => response.json())
  .then((data) => {
    console.log(data);
  });

post request

 fetch(URL), {
    method: "POST",
    body: JSON.stringify({ query: event.currentTarget.value })
  })
    .then(response => response.json())
    .then((data) => {
      console.log(data.hits); // Look at local_names.default
    });

4. API문서를 잘 읽어보자. 사용방법을 잘 익히자.

Post a comment POST '/:channel/messages'
Get messages GET '/:channel/messages'

문서에 이런식으로 명시되어있는데 요청 방법에 따라 이렇게 url을 (:something)부분은 template literal을 사용하여 수정하라는 말

good api == documented well

유용한 관련 리소스
https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fetch
https://ko.javascript.info/fetch (header option 참고)

profile
Hello all 👋🏻 📍London

0개의 댓글