일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
- ChatGPT
- TS
- 팀워크최고
- Expo
- 알고리즘기초주차
- REACT
- 웹개발종합반
- 알pdf #파일탐색기미리보기안될때
- 스파르타코딩클럽
- 리액트
- 사전준비
- TDD
- Programmers
- 맥린이
- 프로그래머스
- 멍친구
- 달리기반
- 항해99
- 프론트엔드
- 7기
- Ai
- 챗GPT
- typeScript
- ReactNative
- D반8조
- rn
- 코린이
- 실전프로젝트
- NotionAI
- 필수강의
- Today
- Total
FrontEnd :-)
환전(환율) 계산기 만들기 ② BE 본문
FE : React , yarn
BE: Express, npm
BE 최종 코드
//app.js
const express = require("express");
const app = express();
const port = 8080;
const { default: fetch } = require("node-fetch");
//cors 추가하면 ajax 잘됨 npm install cors
const cors = require("cors");
const corsOptions = {
origin: 'http://localhost:3000',
credential: true
}
app.use(cors(corsOptions));
//latest API 가져와서 데이터 저장
let date = "";
let rates = [];
fetch('https://api.exchangerate.host/latest?base=USD')
.then((resp) => resp.json())
.then((data) => (
date = data.date,
// console.log("date", date),
rates = data.rates
)).catch(
console.log("Failed to get data from API!")
)
//국가 통화코드 from(currencyCodeFrom), to(currencyCodeTo) 받으면, exchangeRate, date 보내기
app.post("/api", (req, res) => {
// console.log("post", date, rates)
const { from, to } = req.query;
if(from === "USD"){
let exchangeRate = rates[to];
res.send({exchangeRate, date})
} else {
let exchangeRate = rates[to]/rates[from]
res.send({exchangeRate, date})
}
});
//국가, 통화단위 보내기
//select ver.2 - currencyNationList.json
//http://shancarter.github.io/mr-data-converter/ 에서 표를 JSON-Dictionary 로 변환
app.get("/currencynationlist", (req, res) => {
const listData = require('./currencyNationList.json');
res.send({...listData})
})
//서버 실행
app.listen(port, () => {
console.log("서버 실행!!!");
});
=> params => query로 변경
자원의 위치를 요청하는 게 아니라, 값을 보내는 상황이므로 query parameter가 더 적합하다는 판단.
param vs query
- resource를 식별해야하는 상황에서는 Path Variable가 더 적합
- 정렬이나 필터링을 해야하는 상황에서는 Query Parameter가 더 적합
=> cors 조건 수정, 보안 강화
//수정 전
app.use(cors());
//수정 후
const corsOptions = {
origin: 'http://localhost:3000',
credential: true
}
app.use(cors(corsOptions));
=> fetch 사용
fetch 사용 위해 node-fetch 라이브러리 설치
1. fetch로 api 요청
2. rates 리스트를 받아와서 저장해 두고, post 요청 있을 때 사용. => 빨라졌다!!!!!!!!!!!!!!😆
++코드 simplify
//수정 전
if(from === "USD"){
let exchangeRate = rates[to];
res.send({exchangeRate, date})
} else {
let exchangeRate = rates[to]/rates[from]
res.send({exchangeRate, date})
}
//수정 후
let exchangeRate;
if(from === "USD"){
exchangeRate = rates[to];
} else {
exchangeRate = rates[to]/rates[from]
}
res.send({exchangeRate, date})
//수정 한 번 더
let exchangeRate;
(from === "USD") ? exchangeRate = rates[to] : exchangeRate = rates[to]/rates[from];
res.send({exchangeRate, date})
//currencyNationList.json
{
"1": { "currencyCode": "USD", "currencyName": "달러", "nation": "미국" },
"2": { "currencyCode": "JPY", "currencyName": "엔", "nation": "일본" },
"3": { "currencyCode": "EUR", "currencyName": "유로", "nation": "유로" },
"4": { "currencyCode": "CNY", "currencyName": "위안", "nation": "중국" },
"5": { "currencyCode": "HKD", "currencyName": "달러", "nation": "홍콩" },
"6": { "currencyCode": "THB", "currencyName": "바트", "nation": "태국" },
"7": { "currencyCode": "TWD", "currencyName": "달러", "nation": "대만" },
"8": { "currencyCode": "PHP", "currencyName": "페소", "nation": "필리핀" },
"9": { "currencyCode": "SGD", "currencyName": "달러", "nation": "싱가포르" },
"10": { "currencyCode": "AUD", "currencyName": "달러", "nation": "호주" },
"11": { "currencyCode": "VND", "currencyName": "동", "nation": "베트남" },
"12": { "currencyCode": "GBP", "currencyName": "파운드", "nation": "영국" },
"13": { "currencyCode": "CAD", "currencyName": "달러", "nation": "캐나다" },
"14": {
"currencyCode": "MYR",
"currencyName": "링기트",
"nation": "말레이지아"
},
"15": { "currencyCode": "RUB", "currencyName": "루블", "nation": "러시아" },
"16": {
"currencyCode": "ZAR",
"currencyName": "랜드",
"nation": "남아공화국"
},
"17": {
"currencyCode": "NOK",
"currencyName": "크로나",
"nation": "노르웨이"
},
"18": { "currencyCode": "NZD", "currencyName": "달러", "nation": "뉴질랜드" },
"19": { "currencyCode": "DKK", "currencyName": "크로나", "nation": "덴마크" },
"20": { "currencyCode": "MXN", "currencyName": "페소", "nation": "멕시코" },
"21": { "currencyCode": "MNT", "currencyName": "투그릭", "nation": "몽골" },
"24": { "currencyCode": "BRL", "currencyName": "헤알", "nation": "브라질" },
"28": { "currencyCode": "SEK", "currencyName": "크로나", "nation": "스웨덴" },
"29": { "currencyCode": "CHF", "currencyName": "프랑", "nation": "스위스" },
"34": { "currencyCode": "ILS", "currencyName": "셰켈", "nation": "이스라엘" },
"35": { "currencyCode": "EGP", "currencyName": "파운드", "nation": "이집트" },
"36": { "currencyCode": "INR", "currencyName": "루피", "nation": "인도" },
"37": {
"currencyCode": "IDR",
"currencyName": "루피아",
"nation": "인도네시아"
},
"38": { "currencyCode": "CZK", "currencyName": "코루나", "nation": "체코" },
"43": { "currencyCode": "COP", "currencyName": "페소", "nation": "콜롬비아" },
"45": { "currencyCode": "TZS", "currencyName": "실링", "nation": "탄자니아" },
"46": { "currencyCode": "TRY", "currencyName": "리라", "nation": "튀르키예" },
"48": { "currencyCode": "PLN", "currencyName": "즈워티", "nation": "폴란드" },
"49": { "currencyCode": "HUF", "currencyName": "포린트", "nation": "헝가리" },
"50": { "currencyCode": "KRW", "currencyName": "원", "nation": "대한민국" }
}
=> Update JSON 파일 생성으로 외부 api 연결 최소화
국가명으로 select 바꾸기 위해 json 파일 생성 후, 코드 변경 //http://shancarter.github.io/mr-data-converter/ 에서 표(하나은행에서 긁어온 표)를 JSON-Dictionary 로 변환했다.==> 외부 api 사용 3개->1개 로 줄임.
=> API에 존재하지 않는 통화코드 리스트에서 삭제
'JavaScript' 카테고리의 다른 글
환전(환율) 계산기 만들기 ① BE (0) | 2023.03.14 |
---|---|
[Express/node] EJS (0) | 2023.03.01 |
[Express/node] FirstApp (0) | 2023.02.28 |