본문 바로가기
웹/Javascript

fetch

by hihijh826 2023. 8. 3.
728x90
반응형
SMALL

https://velog.io/@ldaehi0205/ajax-fetch-xhr-비동기통신-이해하기#fetch

 

ajax, fetch, xhr 비동기통신 이해하기

기존의 웹 애플리케이션은 브라우저에서 폼을 채우고 이를 웹 서버로 제출(submit)을 하면 하나의 요청으로 웹 서버는 요청된 내용에 따라서 데이터를 가공하여 새로운 웹 페이지 를 작성하고 응

velog.io

참고 출처

(1)fetch

  • 원격 api를 간편하게 호출할 수 있도록 브라우저에서 제공하는 함수
  • 비동기 통신 가능
  • 프로미스를 반환함

fetch ( url, options)

(위치,옵션 )

첫번쨰 인자 : url

두번째 인자 : 옵션 객체 :

→ http 방식(method ) , http 요청 헤더(headers), http 요청 전문(body) 설정 가능

: promise 타입의 객체 반환

api 호출 성공 : response 객체(promise 타입의 객체) 를 resolve(함수인자)

api 호출 실패 : error 객체(promise 타입의 객체) 를 reject(함수인자)

fetch(url, options)
  .then((response) => console.log("response:", response))
  .catch((error) => console.log("error:", error))

<에러 처리 방법>

fetch("<https://3000.typicode.com/posts>", {
 method: "POST", // 옵션 객체의 : http 방식
 headers: {
   "Content-Type": "application/json", //json전송한다는 뜻 (http 요청 헤더)
 },
 body: JSON.stringify({ 
   title: "Test",
   body: "I am testing!",
   userId: 1, //http 요청 전문 
 }),
})
 .then((response) => response.json())
 .then((data) => console.log(data))

JSON.stringify : 객체를 JSON문자열로 변환

{a:1} >>>"{a:1}"

json에서 불러오기

fetch('student.json') //json 파일을 읽어옴  //option 생략 ->get 
.then(response => response.json()) //json 파일을 객체로 변환
.then(json=>{
	let output = '';
	json.forEach(student => {
		output +='
			<h2> ${student.name}</h2> ';
	});
	document.querySelector('#result').innerHTML = output;
})
.catch(error => console.log(error);  //오류가 발생하면 오류를 보여줌 
728x90
반응형
LIST

' > Javascript' 카테고리의 다른 글

canvas  (0) 2023.08.03
동기 /비동기  (0) 2023.08.03
서버에서 자료 가져오기  (0) 2023.08.03
json이란  (0) 2023.08.03
http 통신  (0) 2023.08.03