프론트엔드 엔지니어로써 서버에 있는 데이터를 가져올 때에는 fetch와 axios등 여러가지를 사용한다. 이를 깔쌈하게 정리해두면 프로젝트 할 때 도움이 될 것 같다.
GET
fetch('https://example.com/posts/1')
.then(response => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.then(json => console.log(json))
.catch(error => console.error(error))
POST
fetch('https://example.com/posts', {
method: 'POST',
body: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
}),
headers: {
'Content-type': 'application/json; charset=UTF-8'
}
})
.then(response => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.then(json => console.log(json))
.catch(error => console.error(error))
PUT
fetch('https://example.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 => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.then(json => console.log(json))
.catch(error => console.error(error))
DELETE
fetch('https://example.com/posts/1', {
method: 'DELETE'
})
.then(response => {
if (!response.ok) {
throw new Error(response.statusText);
}
return response.json();
})
.then(json => console.log(json))
.catch(error => console.error(error))
GET
const axios = require('axios');
axios.get('https://example.com/posts/1')
.then(response => console.log(response.data))
.catch(error => console.error(error))
POST
const axios = require('axios');
axios.post('https://example.com/posts', {
title: 'foo',
body: 'bar',
userId: 1
})
.then(response => console.log(response.data))
.catch(error => console.error(error))
PUT
const axios = require('axios');
axios.put('https://example.com/posts/1', {
title: 'foo',
body: 'bar',
userId: 1
})
.then(response => console.log(response.data))
.catch(error => console.error(error))
DELETE
const axios = require('axios');
axios.delete('https://example.com/posts/1')
.then(response => console.log(response.data))
.catch(error => console.error(error))
좋은 글이네요. 공유해주셔서 감사합니다.