API란?
https://blckchainetc.tistory.com/199
Kakao Developers 로그인 -> 제품 -> 지도/로컬 클릭 -> 개발가이드 -> 주소검색, 좌표로 주소 변환하기 내용 준비
어떻게 API 써야하는지 요청을 어떻게 보내야하는지, 응답을 어떻게 줄건지 친절하게 다 나와있다.
https://developers.kakao.com/docs/latest/ko/local/dev-guide#coord-to-address
카카오 주소 API 가져오기
1. 기본 VisualStudio 세팅
$ npm init
$ npm install expres nunjucks
파일 server.js
const express = require('express');
const nunjucks = require('nunjucks');
const app = express();
nunjucks.configure('views',{
express:app,
})
app.set('view engine', 'html');
app.get('/', (req,res)=>{
res.render('index.html');
})
app.listen(3000,()=>{
console.log('server start port : 3000')
})
폴더 views - 파일 index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
ㅎㅇ
</body>
</html>
server on -> index.html 이 잘 render되는지 확인
2. html - page loaded 되면 실행될 함수 만들기 (head쪽에 넣기 위해)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded',init);
function init(){
console.log('js불러오기')
}
</script>
</head>
<body>
ㅎㅇ
</body>
</html>
-> console.log 찍히나 확인
3. 카카오쪽에 요청하는 코드 작성 / 비동기 fetch 사용
kakao developers 에 나온 요청 형식을 잘 보고 그대로 써주기
요청코드 예시를 먼저 그대로 복사
* fetch 의 첫번째 인자값 : url , 두번째 : 설정값
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
/*
주소 요청 url : https://dapi.kakao.com/v2/local/search/address.json?analyze_type=similar&page=1&size=10&query=
REST API : f219cecc72f1eb147e757978ac0e323f
*/
document.addEventListener('DOMContentLoaded', init);
async function init() {
const searchBtn = document.querySelector('#addressSearch');
searchBtn.addEventListener('click',getAddress);
}
async function getAddress(){
const addressInput = document.querySelector('#addressInput');
const addressList = document.querySelector('#addressList');
let options = {
method: 'GET',
headers: {
'Authorization': 'KakaoAK f219cecc72f1eb147e757978ac0e323f'
}
}
let result = await fetch('https://dapi.kakao.com/v2/local/search/address.json?analyze_type=similar&page=1&size=10&query='+addressInput.value, options);
let json = await result.json();
console.log(result)
console.log(json)
}
</script>
</head>
<body>
<div>
<input type="text" id="addressInput" name="addressInput" placeholder="주소를 입력해 주세요">
<button id="addressSearch">주소 검색하기</button>
</div>
<ul id="addressList">
</ul>
</body>
</html>
4. 나온 결과 li 로 만들어서 내용 넣고 appendChild
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', init);
async function init() {
const searchBtn = document.querySelector('#addressSearch');
searchBtn.addEventListener('click',getAddress);
}
async function getAddress(){
const addressInput = document.querySelector('#addressInput');
const addressList = document.querySelector('#addressList');
let options = {
method: 'GET',
headers: {
'Authorization': 'KakaoAK f219cecc72f1eb147e757978ac0e323f'
}
}
let result = await fetch('https://dapi.kakao.com/v2/local/search/address.json?analyze_type=similar&page=1&size=10&query='+addressInput.value, options);
let json = await result.json();
json.documents.forEach(v=>{
const li = document.createElement('li');
li.innerHTML=v.address_name;
addressList.appendChild(li);
});
}
</script>
5. dataset을 사용해서 x, y 값 나오게 나기
json.documents.forEach(v=>{
const li = document.createElement('li');
li.innerHTML=v.address_name;
li.dataset.x = v.x;
li.dataset.y = v.y;
addressList.appendChild(li);
});
dataset => 값을 쉽게 꺼내오기 위해 html이 친절히 만들어쥼
6. 해당 주소 클릭하면 textbox 에 주소값 넣기
html 추가
<body>
<div>
<input type="text" id="addressInput" name="addressInput" placeholder="주소를 입력해 주세요">
<button id="addressSearch">주소 검색하기</button>
</div>
<ul id="addressList">
</ul>
<input type="text" name="addressNumber" id="addressNumber" size="10" placeholder="우편번호">
<input type="text" name="address1" id ="address1" size="40" placeholder ="주소">
<input type="text" name="address2" id ="address2" placeholder="상세주소">
</body>
이미 가져온 주소는 details 가 없어서 아래 '좌표로 주소 변환하기' 한 번 더 이용
kakao developers에서 가져온 예제 request
curl -v -X GET "https://dapi.kakao.com/v2/local/geo/coord2regioncode.json?x=127.1086228&y=37.4012191" \
-H "Authorization: KakaoAK {REST_API_KEY}"
코드 작성
url 에 x, y 값 넣어서 요청
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', init);
async function init() {
const searchBtn = document.querySelector('#addressSearch');
searchBtn.addEventListener('click',getAddress);
}
async function getAddress(){
const addressInput = document.querySelector('#addressInput');
const addressList = document.querySelector('#addressList');
let options = {
method: 'GET',
headers: {
'Authorization': 'KakaoAK f219cecc72f1eb147e757978ac0e323f'
}
}
let result = await fetch('https://dapi.kakao.com/v2/local/search/address.json?analyze_type=similar&page=1&size=10&query='+addressInput.value, options);
let json = await result.json();
addressList.innerHTML=''; //다시 reset
json.documents.forEach(v=>{
const li = document.createElement('li');
li.innerHTML=v.address_name;
li.dataset.x = v.x;
li.dataset.y = v.y;
addressList.appendChild(li);
li.addEventListener('click', getAddressdetail);
});
}
async function getAddressdetail(){
const addressNumber=document.querySelector('#addressNumber');
const address1=document.querySelector('#address1');
let x = this.dataset.x;
let y = this.dataset.y;
let url=`https://dapi.kakao.com/v2/local/geo/coord2address.json?input_coord=WGS84&x=${x}&y=${y}`;
let options={
method:'GET',
headers:{
'Authorization' : 'KakaoAK f219cecc72f1eb147e757978ac0e323f'
}
}
let result = await fetch(url,options);
let json = await result.json();
console.log(json);
}
</script>
console.log(json)확인
.json() 쓰는 이유 ?
fetch 의 반환 값 = promise 객체 -> 안의 body 영역을 일기 위해
body 영역 type -> application/json 으로 오기 떄문에 상태 body내용 읽을 때 .text() 쓰면 되었는데 우리 결과값 읽을 때 json 형태로 바로 쓰기 위해 .json()을 씀
API 결과는 항상 json or XML
응답 헤더 내용 : contecntType = application/json
읽을 때도 json으로 받으면 편하게 사용할 수 있다. 이걸 구분하려면 contenttype을 보기 !
json 값 console.log 참고해서 아래 value 에 넣어주기
async function getAddressdetail(){
const addressNumber=document.querySelector('#addressNumber');
const address1=document.querySelector('#address1');
let x = this.dataset.x;
let y = this.dataset.y;
let url=`https://dapi.kakao.com/v2/local/geo/coord2address.json?input_coord=WGS84&x=${x}&y=${y}`;
let options={
method:'GET',
headers:{
'Authorization' : 'KakaoAK f219cecc72f1eb147e757978ac0e323f'
}
}
let result = await fetch(url,options);
let json = await result.json();
console.log(json);
const addressName = json.documents[0].road_address.address_name;
const buildingName = json.documents[0].road_address.building_name;
const zone_no = json.documents[0].road_address.zone_no;
address1.value=`${addressName} ${buildingName}`;
addressNumber.value=zone_no;
}
7. 길주소 road_address가 없는 부분 오류 고치기
async function getAddressdetail(){
const addressNumber=document.querySelector('#addressNumber');
const address1=document.querySelector('#address1');
let x = this.dataset.x;
let y = this.dataset.y;
let url=`https://dapi.kakao.com/v2/local/geo/coord2address.json?input_coord=WGS84&x=${x}&y=${y}`;
let options={
method:'GET',
headers:{
'Authorization' : 'KakaoAK f219cecc72f1eb147e757978ac0e323f'
}
}
let result = await fetch(url,options);
let json = await result.json();
if(json.documents[0].road_address==null){
let address_name = json.documents[0].address.address_name;
address1.value=address_name;
}else{
const addressName = json.documents[0].road_address.address_name;
const buildingName = json.documents[0].road_address.building_name;
const zone_no = json.documents[0].road_address.zone_no;
address1.value=`${addressName} ${buildingName}`;
addressNumber.value=zone_no;
}
}
아직 road_address가 없는 주소의 우편번호가 안나오는 오류가 있음
8. 아무것도 입력하지않고 버튼 누를 때 alert 만들기
async function getAddress(){
const addressInput = document.querySelector('#addressInput');
const addressList = document.querySelector('#addressList');
if(addressInput.value==''){
alert('주소를 입력해주세요');
addressInput.focus();
return false;
}
9. 결과값이 없을 경우 메세지
addressList.innerHTML='';
if(json.documents.length==0){
addressList.innerHTML='결과값이 존재하지 않습니다.';
return false;
}
json.documents.forEach(v=>{
const li = document.createElement('li');
li.innerHTML=v.address_name;
li.dataset.x = v.x;
li.dataset.y = v.y;
addressList.appendChild(li);
li.addEventListener('click', getAddressdetail);
});
전체 코드
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', init);
async function init() {
const searchBtn = document.querySelector('#addressSearch');
searchBtn.addEventListener('click',getAddress);
}
async function getAddress(){
const addressInput = document.querySelector('#addressInput');
const addressList = document.querySelector('#addressList');
if(addressInput.value==''){
alert('주소를 입력해주세요');
addressInput.focus();
return false;
}
let options = {
method: 'GET',
headers: {
'Authorization': 'KakaoAK f21147e757978ac0e323f'
}
}
let result = await fetch('https://dapi.kakao.com/v2/local/search/address.json?analyze_type=similar&page=1&size=10&query='+addressInput.value, options);
let json = await result.json();
addressList.innerHTML='';
if(json.documents.length==0){
addressList.innerHTML='결과값이 존재하지 않습니다.';
return false;
}
json.documents.forEach(v=>{
const li = document.createElement('li');
li.innerHTML=v.address_name;
li.dataset.x = v.x;
li.dataset.y = v.y;
addressList.appendChild(li);
li.addEventListener('click', getAddressdetail);
});
}
async function getAddressdetail(){
const addressNumber=document.querySelector('#addressNumber');
const address1=document.querySelector('#address1');
let x = this.dataset.x;
let y = this.dataset.y;
let url=`https://dapi.kakao.com/v2/local/geo/coord2address.json?input_coord=WGS84&x=${x}&y=${y}`;
let options={
method:'GET',
headers:{
'Authorization' : 'KakaoAK f21b147e757978ac0e323f'
}
}
let result = await fetch(url,options);
let json = await result.json();
if(json.documents[0].road_address==null){
let address_name = json.documents[0].address.address_name;
address1.value=address_name;
}else{
const addressName = json.documents[0].road_address.address_name;
const buildingName = json.documents[0].road_address.building_name;
const zone_no = json.documents[0].road_address.zone_no;
address1.value=`${addressName} ${buildingName}`;
addressNumber.value=zone_no;
}
}
</script>
</head>
<body>
<div>
<input type="text" id="addressInput" name="addressInput" placeholder="주소를 입력해 주세요">
<button id="addressSearch">주소 검색하기</button>
</div>
<ul id="addressList">
</ul>
<input type="text" name="addressNumber" id="addressNumber" size="10" placeholder="우편번호">
<input type="text" name="address1" id ="address1" size="40" placeholder ="주소">
<input type="text" name="address2" id ="address2" placeholder="상세주소">
</body>
</html>
'블록체인 기반 핀테크 및 응용 SW개발자 양성과정 일기' 카테고리의 다른 글
[52일차 복습] Javascript node.js [JWT] token 토큰 암호화해서 브라우저 cookie에 저장하기 (0) | 2021.05.27 |
---|---|
[52일차]20210527 JWT token 토큰 만들어 브라우저 cookie에 저장하기 (0) | 2021.05.27 |
[51일차]20210526 API 카카오 주소 가져오기 (0) | 2021.05.26 |
[50일차 복습] HTTP protocol 구조 개요와 예제 (1) | 2021.05.26 |
[50일차] 20210525 HTTP post, get 공부 (0) | 2021.05.26 |