Node.js์์ API ์๋ฒ ๋ง๋ค๊ธฐ
์์คํ
์ ํน์ ๋ฐ์ดํฐ ํน์ ํน์ ๊ธฐ๋ฅ์ ์ฌ์ฉํ๊ณ ์ถ์ ๋ค๋ฅธ Third-party ์์คํ
์๊ฒ
ํ๋ก๊ทธ๋จ ์ฝ๋ ๋
ธ์ถ์ํค์ง ์๊ณ , ํน์ ๋ฐ์ดํฐ๋ฒ ์ด์ค์ ์ง์ ์ฐ๊ฒฐํด์
๋ฐ์ดํฐ๋ฅผ ์ปจ๋ฅ์
ํ๊ณ ์ปจํธ๋กคํ๋ ๊ถํ์ ์ฃผ์ง ์๊ณ ์์คํ
์์ ์ ๊ณตํ๋ ๊ธฐ๋ฅ์ด๋
๋ฐ์ดํฐ๋ฅผ ์ ๊ณตํ ๋ API ์๋ฒ ์ฌ์ฉ
REST API ๋ฐฉ์; ์น HTTP๋ฅผ ์ด์ฉํด์ API ์๋ฒ์ URL ๋ฐฉ์์ผ๋ก ๋ฐ์ดํฐ ํธ์ถ
const express = require ( 'express' ) ;
const app = express ( ) ;
const server = app . listen ( 3001 , function ( req , res ) {
console . log ( 'Start Server : localhost:3001' ) ;
} ) ;
// : (์ฝ๋ก ) ์๋ path์๋ ์ด๋ค ๊ฐ์ด๋ ๋ค์ด์ฌ ์ ์์
app . get ( '/api/users/:type' , async ( req , res ) => {
let { type } = req . params ;
if ( type == 'seoul' ) {
let data = [
{
name : 'ํ๊ธธ๋' ,
city : 'seoul' ,
} ,
{
name : '๊น์ฒ ์' ,
city : 'seoul' ,
} ,
] ;
res . send ( data ) ;
} else if ( type == 'jeju' ) {
let data = [
{
name : '๋ฐ์ง์ฑ' ,
city : 'jeju' ,
} ,
{
name : '์ํฅ๋ฏผ' ,
city : 'jeju' ,
} ,
] ;
res . send ( data ) ;
} else {
res . send ( 'Type is not correct.' ) ;
}
} ) ;
key ์ถ๊ฐ (์๋ฌด๋ ์ ๋ณด ๋ฐ์๊ฐ๋ฉด ์๋จ)
uuid-apikey (API key ์์ฑํด์ฃผ๋ ๋ชจ๋)
const express = require ( 'express' ) ;
const app = express ( ) ;
const uuidAPIKey = require ( 'uuid-apikey' ) ;
const server = app . listen ( 3001 , function ( req , res ) {
console . log ( 'Start Server : localhost:3001' ) ;
} ) ;
const key = {
apiKey : '5PB37WM-5ACM5D2-QV7HB6X-GX5VDVV' ,
uuid : '2d9633f2-2a99-42b4-becf-159b874bb6ef' ,
} ;
// : (์ฝ๋ก ) ์๋ path์๋ ์ด๋ค ๊ฐ์ด๋ ๋ค์ด์ฌ ์ ์์
app . get ( '/api/users/:apikey/:type' , async ( req , res ) => {
let { apikey, type } = req . params ;
if ( ! uuidAPIKey . isAPIKey ( apikey ) || ! uuidAPIKey . check ( apikey , key . uuid ) ) {
res . send ( 'apikey is not valid' ) ;
} else {
if ( type == 'seoul' ) {
let data = [
{
name : 'ํ๊ธธ๋' ,
city : 'seoul' ,
} ,
{
name : '๊น์ฒ ์' ,
city : 'seoul' ,
} ,
] ;
res . send ( data ) ;
} else if ( type == 'jeju' ) {
let data = [
{
name : '๋ฐ์ง์ฑ' ,
city : 'jeju' ,
} ,
{
name : '์ํฅ๋ฏผ' ,
city : 'jeju' ,
} ,
] ;
res . send ( data ) ;
} else {
res . send ( 'Type is not correct.' ) ;
}
}
} ) ;
express ๋ชจ๋; node.js๋ก ์น ์๋ฒ ๋น ๋ฅด๊ฒ ๊ตฌ์ถํ ์ ์๋๋ก ํด์ฃผ๋ ๋ชจ๋
Postman; ๊ฐ๋ฐํ API๋ฅผ ํ
์คํธํ ์ ์๋ API ๊ฐ๋ฐ ์์ฐ์ฑ ๋์ฌ์ฃผ๋ ํ๋ซํผ
Reference