안내
아래에서 Fetch API를 사용하는 예를 찾을 수 있지만 다른 언어로 JSONPlaceholder를 사용할 수 있습니다.
브라우저 콘솔에 코드를 복사하여 붙여 넣어 JSONPlaceholder를 빠르게 테스트 할 수 있습니다.
리소스 얻기
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then((response) => response.json())
.then((json) => console.log(json));
? Output
{
id: 1,
title: '...',
body: '...',
userId: 1
}
모든 리소스 나열
fetch('https://jsonplaceholder.typicode.com/posts')
.then((response) => response.json())
.then((json) => console.log(json));
? Output
[
{ id: 1, title: '...' /* ... */ },
{ id: 2, title: '...' /* ... */ },
{ id: 3, title: '...' /* ... */ },
/* ... */
{ id: 100, title: '...' /* ... */ },
];
리소스 생성
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((json) => console.log(json));
? Output
{
id: 101,
title: 'foo',
body: 'bar',
userId: 1
}
중요 : 리소스는 서버에서 실제로 업데이트 되지 않지만 마치 가짜로 처리됩니다.
자원 업데이트
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'PUT',
body: JSON.stringify({
id: 1,
title: 'foo',
body: 'bar',
userId: 1,
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((json) => console.log(json));
? Output
{
id: 1,
title: 'foo',
body: 'bar',
userId: 1
}
중요 : 리소스는 서버에서 실제로 업데이트 되지 않지만 마치 가짜로 처리됩니다.
리소스 패치
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'PATCH',
body: JSON.stringify({
title: 'foo',
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
})
.then((response) => response.json())
.then((json) => console.log(json));
? Output
{
id: 1,
title: 'foo',
body: '...',
userId: 1
}
중요 : 리소스는 서버에서 실제로 업데이트 되지 않지만 마치 가짜로 처리됩니다.
리소스 삭제
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'DELETE',
});
중요 : 리소스는 서버에서 실제로 업데이트 되지 않지만 마치 가짜로 처리됩니다.
리소스 필터링
기본 필터링은 쿼리 매개 변수를 통해 지원됩니다.
// This will return all the posts that belong to the first user
fetch('https://jsonplaceholder.typicode.com/posts?userId=1')
.then((response) => response.json())
.then((json) => console.log(json));
중첩 된 리소스 나열
한 수준의 중첩 된 경로를 사용할 수 있습니다.
// This is equivalent to /comments?postId=1
fetch('https://jsonplaceholder.typicode.com/posts/1/comments')
.then((response) => response.json())
.then((json) => console.log(json));
사용 가능한 중첩 경로는 다음과 같습니다.
등록된 댓글이 없습니다.