fetch api

Jinny·2022년 4월 4일
0

vanilla js

목록 보기
1/5

❓자바스크립트를 사용하면 필요할 때 서버에 네트워크 요청을 보내고 새로운 정보를 받아오는 일을 할 수 있다!

⭐AJAX(Asynchronous JavaScript And XML, 비동기적 JavaScript와 XML)라는 용어를 들어봤을것이다! AJAX는 서버에서 추가 정보를 비동기적으로 가져올 수 있게 해주는 기술이다!

ajax종류

  1. XHR
  2. jQuery
  3. fetch

3가지의 종류에서 jQueryfetch를 사용해봤는데 XHR은 안써봐서.. 패스.. jQueryfetch가 가장 유용하게 쓰일 것같다!!

👌프로젝트를 진행하며 ajax로 처리를 해야할 일이 생겼는데
요즘은 jquery보다 vanilla js로 하는게 좋다고 들었던거 같아 js연습도 할겸
vanilla js로 구현해보기로 했다!!

fetch와 jquery의 차이점!

fetch()로 부터 반환되는 Promise 객체는 HTTP error 상태를 반환하지 않는다!
HTTP Status Code가 404나 500을 반환해도 동일하다.
대신 ok 상태가 falseresolve가 반환되며, 네트워크 장애나 요청이 완료되지 못한 상태에는 reject가 반환된다!
보통 fetch는 쿠키를 보내거나 받지 않는다. 사이트에서 사용자 세션을 유지 관리해야하는 경우 인증되지 않는 요청이 발생한다!! 쿠키를 전송하기 위해서는 자격증명(credentials) 옵션을 반드시 설정해야 한다!

출처 MDN : https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fetch

fetch 기본 문법(GET)

	// 일반적인 GET요청 시 작성하는 문법이다.
	fetch('http://example.com/movies.json')
  .then(response => response.json())
  .then(data => console.log(data)); //자바스크립트 객체로 변환한다!
  .catch(error => console.log(error));

fetch() 함수는 첫번째 인자로 URL, 두번째 인자로 옵션 객체를 받고, Promise 타입의 객체를 반환한다!

반환된 객체는 API 호출이 성공했을 경우에는 .then으로 resolve 객체를 리턴받고, 실패했을 경우에는 .catch로 reject 객체를 리턴받는다.

fetch 기본 문법(POST)

fetch("http://example.com/movies.json/post", {
  method: "POST", 	// GET도 넣을 수는 있지만 안넣어도 상관없다. default는 get
  headers: {
    "Content-Type": "application/json",	// json형식의 값을 넘겨줌을 header에 명시
  },
  body: JSON.stringify({	//javascript 객체를 json객체로 변환한다.
    title: "Test",
    body: "I am testing!",
    userId: 1,
  }),
})
  .then((response) => response.json())
  .then((data) => console.log(data))

header는 new로 생성도 가능하다!
let myHeaders = new Headers(); 와 같이 생성할 수 있다.
생성한 Header에는 속성들을 추가, 제거, 조회 할 수 있다.
다음과 같은 메소드를 제공한다.
append(), delete(), entries(), forEach(), get(), has(), keys(), set(), values(), getAll()

new로 헤더 만들어서 넣기

	let myHeaders = new Headers();

	myHeaders.append('Content-Type', 'text/xml');
	myHeaders.get('Content-Type')

	fetch("http://example.com/movies.json/post", {
        method: "POST", 	// GET도 넣을 수는 있지만 안넣어도 상관없다. default는 get
        headers: myHeaders,
        body: JSON.stringify({	//javascript 객체를 json객체로 변환한다.
          title: "Test",
          body: "I am testing!",
          userId: 1,
        }),
      })
        .then((response) => response.json())
        .then((data) => console.log(data))
    

fetch 기본 문법(PUT)

fetch("http://example.com/movies.json/put", {
  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))

method가 put이 되는 것 이외에는 POST와 크게 다를건 없다!

fetch 기본 문법(DELETE)

fetch("http://example.com/movies.json/post1", {
  method: "DELETE",
})
  .then((response) => response.json())
  .then((data) => console.log(data))

보낼 데이터가 없어 body나 header는 없다!

⁉️csrf토큰 보내기

프로젝트 진행 중 spring security POST요청시에는 프론트에서 csrf토큰을 같이 넘겨주어야한다는 얘기를 들어 하는법을 찾아보았다!
방법은 아주 간단했다!
1. html파일 head부분에 아래 _csrf값을 넣어놓는 meta태그를 넣어놓는다!

	<head>
    <meta id="_csrf" name="_csrf" content="{{_csrf.token}}"/>
    <meta id="_csrf_header" name="_csrf_header" content="{{_csrf.headerName}}"/>
	</head>

위 예제는 spring template mustache로 진행해 content안에 {}로 감싸져있습니다!

  1. fetch에 헤더 부분에 해당하는 csrf토큰값을 받아올수있도록한다.
	//방법 1
	const header = document.querySelector('meta[name="_csrf_header"]').content;
    const token = document.querySelector('meta[name="_csrf"]').content;

	fetch("/test/user", {
            method: "POST",
            headers: {
                'header': header,
              	'X-Requested-With': 'XMLHttpRequest',
                "Content-Type": "application/json",
                'X-CSRF-Token': token	// header에 X-CSRF-Token부분에 토큰값이 들어가 정상적으로 POST값이 넘어가는 것을 볼 수 있다!
            },
            body: JSON.stringify(postData)
        })
	//방법2
	fetch("/test/user", {
            method: "POST",
            headers: {
                'header': document.querySelector('meta[name="_csrf"]').content,
                "Content-Type": "application/json"
                'X-CSRF-Token': document.querySelector('meta[name="_csrf_header"]').content;
      // 바로 X-CSRF-Token에 값을 주는 법!
            },
            body: JSON.stringify(postData)
        })

위의 코드를 완성해 토큰을 정상적으로 넘길 수 있었따!⭐
이상한점이나 수정할 부분, 궁금한 부분이 있다면 댓글 남겨주세요!

참고 :
https://developer.mozilla.org/ko/docs/Web/API/Fetch_API
https://velog.io/@sham/Fetch%EB%9E%80-%EB%AC%B4%EC%97%87%EC%9D%B8%EA%B0%80#%EC%9E%91%EB%8F%99-%EB%B0%A9%EC%8B%9D
https://velog.io/@prayme/Fetch-API#post-%EC%9A%94%EC%B2%AD%ED%95%98%EA%B8%B0

profile
프론트엔드 공부중입니다!

0개의 댓글