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));
}, []);
`
직접 사용한 코드
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은 기본 옵션이기에 써줄 필요가 없다.
직접 사용한 코드
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은 이번에 사용하지 못했다
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와 흡사하다
직접 사용한 코드
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('잘못된 요청입니다');
}
});
};