[통신] - Async, Await, fetch, axios 각 차이

2025. 9. 16. 13:08FRONTEND/React

 

- 게시판 글 작성

 fetch("http://localhost:8082/api/board", {
    method: "POST",
    headers: {
        "Content-Type": "application/json;charset=utf-8"
    },
    body: JSON.stringify(board)
})


.then((res) => {
    console.log(1, res);
    if (res.status === 201) {
        return res.json();
    } else {
        return null;
    }
})
.then((res) => { // 결과를 받는다.
    console.log("정상", res);
    if (res !== null) {
        navigate('/boardList') // props.history.push('/boardLst');
    } else {
        alert('게시글 작성에 실패했습니다.');
    }
}) // 실패
.catch((error) => {
    console.log("실패", error);
})

 

 

- 게시판 목록 조회

 useEffect(() => {
    fetch("http://localhost:8082/api/boardList", {
        method: "GET"
    })
    .then(res => res.json() // 응답이 오면, javascript object로 바꾸겠다.
    )
    .then(res => {
        console.log(1, res);
        setBoardList(res); // res값으로 boardList 변경을 해서 리스트가 뿌려진다.
    })
}, []); // []은 디펜던시인데, setState)로 랜더링될때마다 실행되면 안되고, 1번만 실행되도록 빈배열을 넣어둔다.