Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
31 |
Tags
- 파이썬
- 클래스컴포넌트
- 버블정렬
- State
- React
- 부트스트랩
- React Hook
- 선택정렬
- 리액트
- 크롤링
- render
- habit tracker
- 제이쿼리
- 팬명록
- pycharm
- API
- 기초문법
- 실시간데이터
- python
- 배포
- JavaScript
- og tag
- get방식
- 함수컴포넌트
- 스파르타코딩클럽 완주
- 삽입정렬
- 정렬 알고리즘
- nohup
- mongodb
- 를
Archives
- Today
- Total
Yeonn's 기록하며 성장하는 개발일지 :)
[API호출] Fetch( ) 본문
fetch() 함수는 첫번째 인자로 URL,
두번째 인자로 옵션 객체를 받고
*옵션객체
HTTP 방식(method): POST,PUT,DELETE (GET = 디폴트값),
HTTP 요청 헤더(headers),
HTTP 요청 전문(body) 등을 설정
응답(response) 객체로 부터는
HTTP 응답 상태(status),
HTTP 응답 헤더(headers),
HTTP 응답 전문(body) 등을 읽어올 수 있다.
; fetch() 함수는 디폴트로 GET 방식으로 작동하고,
GET 방식은 요청 전문을 받지 않기 때문에 옵션 인자가 필요가 없다.
Promise 타입의 객체를 반환합니다.
반환된 객체는, API 호출이 성공했을 경우에는 응답(response) 객체를 resolve하고,
실패했을 경우에는 예외(error) 객체를 reject합니다.
GET
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => response.json())
.then((data) => console.log(data));
이 메서드를 호출하면, 응답객체로부터 JSON포멧의 응답전문을 자바스크립트 객체로 변환하여 얻을 수 있다.
{
"userId": 1,
"id": 1,
"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
"body": "quia et suscipit↵suscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto"
}
POST
method 옵션을 POST로 지정해주고,
headers 옵션을 통해 JSON 포멧을 사용한다고 알려줘야 하며,
요청 전문을 JSON 포멧으로 직렬화화여 가장 중요한 body 옵션에 설정해줍니다.
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Test",
body: "I am testing!",
userId: 1,
}),
})
.then((response) => response.json())
.then((data) => console.log(data));
응답객체의 json( ) 메서드를 호출하면 응답전문을 객체형태로 얻을 수 있다.
{title: "Test", body: "I am testing!", userId: 1, id: 101}
PUT, DELETE
- PUT ; method 옵션만 PUT으로 설정한다는 점 빼놓고는 POST 방식과 매우 흡사하다. (수정)
fetch("https://jsonplaceholder.typicode.com/posts/1", {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Test",
body: "I am testing!",
userId: 1,
}),
})
.then((response) => response.json())
.then((data) => console.log(data));
{title: "Test", body: "I am testing!", userId: 1, id: 1}
- DELETE ; 보낼 데이터가 없기때문에 header, body옵션이 필요가 없다.
fetch("https://jsonplaceholder.typicode.com/posts/1", {
method: "DELETE",
})
.then((response) => response.json())
.then((data) => console.log(data));
'개발의 모든것 > Javascript' 카테고리의 다른 글
생성자함수 (0) | 2022.03.11 |
---|---|
[HTTP상태코드 정리] (0) | 2022.02.27 |
Promise (0) | 2022.02.27 |
브라우저 동작원리 (0) | 2022.01.16 |
자바스크립트 개념과 특징 (0) | 2022.01.16 |