본문 바로가기
카테고리 없음

프록시 서버는 요청을 중계해주는 서버

by 강아지톡톡-아지톡 2024. 7. 15.
반응형

프록시 서버는 요청을 중계해주는 서버 

서버 측 프록시 설정이 필요할 경우, 우리는 클라이언트에서 직접 공공 데이터 포털 API를 호출하는 대신, 중간에 프록시 서버를 두어 클라이언트의 요청을 받아 공공 데이터 포털 API로 전달하고, 그 응답을 다시 클라이언트로 전달하는 방식을 사용합니다.

프록시 서버는 요청을 중계해주는 서버로, 주로 다음과 같은 경우에 사용됩니다:

  1. CORS 문제 해결: 클라이언트와 외부 API 서버 간의 교차 출처 요청 문제를 해결합니다.
  2. 보안: API 키와 같은 민감한 정보를 클라이언트 측 코드에 노출하지 않고 서버 측에서 보호할 수 있습니다.
  3. 추가 로직: 요청 또는 응답에 추가적인 로직을 적용할 수 있습니다.

프록시 서버 예제

Node.js와 Express를 사용하여 간단한 프록시 서버를 설정하는 예제를 설명하겠습니다.

1. Node.js 설치

Node.js가 설치되어 있지 않다면, Node.js 공식 사이트에서 설치합니다.

2. 프로젝트 초기화

새로운 디렉토리를 만들고 npm init -y 명령어를 사용하여 프로젝트를 초기화합니다.

sh
코드 복사
mkdir proxy-server cd proxy-server npm init -y

3. Express 설치

Express를 설치합니다.

sh
코드 복사
npm install express node-fetch

4. 프록시 서버 코드 작성

server.js 파일을 생성하고 다음과 같이 코드를 작성합니다.

javascript
코드 복사
const express = require('express'); const fetch = require('node-fetch'); const app = express(); const PORT = 3000; app.get('/proxy', async (req, res) => { const { currentPage, countPerPage, keyword, confmKey } = req.query; const apiUrl = `https://business.juso.go.kr/addrlink/addrLinkApi.do?currentPage=${currentPage}&countPerPage=${countPerPage}&keyword=${encodeURIComponent(keyword)}&confmKey=${confmKey}`; try { const response = await fetch(apiUrl); const data = await response.text(); res.set('Content-Type', 'application/xml'); res.send(data); } catch (error) { res.status(500).send('Server Error'); } }); app.listen(PORT, () => { console.log(`Proxy server running on http://localhost:${PORT}`); });

5. 프록시 서버 실행

프록시 서버를 실행합니다.

sh
코드 복사
node server.js

프록시 서버가 http://localhost:3000에서 실행됩니다.

클라이언트 코드 수정

프록시 서버를 통해 API 요청을 보내도록 클라이언트 코드를 수정합니다.

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>한글 주소를 영문 주소로 변환하기</title>
    <script>
        async function convertAddress() {
            const koreanAddress = document.getElementById('koreanAddress').value;
            const currentPage = 1;
            const countPerPage = 10;
            const confmKey = 'YOUR_API_KEY';  // 공공 데이터 포털에서 발급받은 API 키를 입력합니다
            const apiUrl = `http://localhost:3000/proxy?currentPage=${currentPage}&countPerPage=${countPerPage}&keyword=${encodeURIComponent(koreanAddress)}&confmKey=${confmKey}`;

            try {
                const response = await fetch(apiUrl);
                const data = await response.text();

                // XML 응답을 파싱하여 결과를 추출하는 부분
                const parser = new DOMParser();
                const xmlDoc = parser.parseFromString(data, "application/xml");
                const roadAddrEngElements = xmlDoc.getElementsByTagName("roadAddrEng");
                
                if (roadAddrEngElements.length > 0) {
                    const englishAddress = roadAddrEngElements[0].textContent;
                    document.getElementById('englishAddress').innerText = englishAddress;
                } else {
                    document.getElementById('englishAddress').innerText = '변환에 실패했습니다. 다시 시도해주세요.';
                }
            } catch (error) {
                console.error('Error:', error);
                document.getElementById('englishAddress').innerText = '오류가 발생했습니다. 다시 시도해주세요.';
            }
        }
    </script>
</head>
<body>
    <h1>한글 주소를 영문 주소로 변환하기</h1>
    <p>한글 주소를 입력하세요:</p>
    <input type="text" id="koreanAddress" placeholder="도로명주소, 지번주소 등 입력">
    <button onclick="convertAddress()">변환</button>
    <p>영문 주소:</p>
    <p id="englishAddress"></p>
</body>
</html>

 

 

이제 클라이언트는 프록시 서버를 통해 공공 데이터 포털 API에 접근할 수 있으며, CORS 문제도 해결됩니다. 프록시 서버는 클라이언트의 요청을 받아 공공 데이터 포털 API로 전달하고, 그 응답을 다시 클라이언트로 반환하는 역할을 합니다.

프록시 서버를 통해 클라이언트에서 직접 API 키를 노출하지 않고도 안전하게 API를 호출할 수 있습니다.

한글 주소를 영문 주소로 변환하기

한글 주소를 영문 주소로 변환하기

한글 주소를 입력하세요:

영문 주소:

반응형