Fetch api

신윤지·2022년 6월 5일
0

TIL

목록 보기
3/5
post-thumbnail

fetch 형태

기본형

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

실제 코드

사용할 때는 보통 형태로 쓰게 된다.

useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/users")
      .then((res) => res.json())
      .then((result) => setMonsters(result));
  }, []);
  

`

get

  • 데이터 받아오기(조회)

직접 사용한 코드

const [postList, setPostList] = useState([]);
  const params = useParams();

useEffect(() => {
    fetch(`http://10.58.1.252:8000/reviews/${params.id}`)
      .then(res => res.json())
      .then(productData => setPostList(productData));
  }, []);

GET은 기본 옵션이기에 써줄 필요가 없다.

post

  • 데이터 보내기(등록)

직접 사용한 코드

const postComment = e => {
    e.preventDefault();
    fetch(`http://10.58.1.252:8000/reviews/product/${option}`, {
      method: 'POST',
      headers: {
        Authorization: localStorage.getItem('Authorization'),
      },
      body: JSON.stringify({
        title: title,
        context: context,
        password: password,
      }),
    }).then(res => {
      if (res => res === 'SUCCESS') {
        navigate('/review_page');
      } else {
        alert('잘못된 요청입니다');
      }
    });
  };

put

  • 데이터 수정

put은 이번에 사용하지 못했다

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));

put은 method를 PUT으로 하는 것만 제외하면 POST와 흡사하다

delete

  • 데이터 삭제

직접 사용한 코드

const deletePost = () => {
    fetch(`http://10.58.1.252:8000/reviews/${params.id}`, {
      method: 'DELETE',
    })
      .then(res => res.json())
      .then(result => {
        if (result => result === 'SUCCESS') {
          navigate(-1);
        } else {
          alert('잘못된 요청입니다');
        }
      });
  };

참고 자료
https://www.daleseo.com/js-window-fetch/

0개의 댓글