서버와 클라이언트
요청하는 주체 = 클라이언트
요청에 따른 응답을 주는 = 서버
ex)
날씨앱(클라이언트) : 서울날씨 보내줘
날씨 api (서버) : 서울날씨 27도 임
서버에게 요청하기
http 요청은 fetch API로
fetch('http://서버주소/weather?q=Seoul)
.then(function(resp){
// 응답형식에 따라 resp.text() 가 될 수도 있다
return resp.json()
})
.then(function(json){
console.log(json) // { tempature: 27}
})
API 사용시 유의할 점
서버에 기록할 수도 있나요
let newPost = {
'userId': 1,
'title' : '새 글을 써봤습니다'
'body' : '안녕하세요'
}
fetch('http://서버주소/posts', {
method: 'post',
body: JSON.stringify(newPost)
}).then(function(resp){
return resp.json()
}).then(function(json){
console.log(json) // {id : 123}
})
주요 사이트
koreanjson.com
apistore.co.kr
openweathermap.org/API