개발 노트

public ip 가져오기(axios) 본문

Node

public ip 가져오기(axios)

한츄 2024. 5. 20. 10:52

1. 데이터 fetch로 api호출하기

const axios = require("axios");

let publicIp;
(async () => {
  try {
    const response = await axios.get('https://api64.ipify.org?format=json', {
      httpsAgent: agent
    });
    log('publicIp',response.data.ip);
    publicIp=response.data.ip
  } catch (error) {
    log('Error fetching public IP:', error);
  }
})();

 

 

2. TLS 에러발생 -> ip를 사용하게 허가해줘야함
3. https모듈 설치 및 추가

const https = require('https');

const agent = new https.Agent({
  rejectUnauthorized: false,  // trustServerCertificate: true 와 같은 효과
  // 서버 인증서 검사를 비활성화
});

 

 

4. 정상적으로 ip호출 확인

5. 문자메세지 전송함수에 추가 

// 문자 메시지를 전송하는 함수
async function sendSMSMessages(phoneNumbers, message) {
  try {
    const response = await axios.get('https://api64.ipify.org?format=json', {
      httpsAgent: agent
    });
    const publicIp = response.data.ip;
    log('publicIp', publicIp);

    phoneNumbers.forEach((phoneNumber) => {
      // URL에 포함될 수 있도록 메시지 인코딩
      const encodedMessage = encodeURIComponent("C관제-" + message + "-" + publicIp);
      log("sms - " + message);
      const url = //생략

      axios
        .get(url)
        .then(() => {
          log(`${phoneNumber}로 알림 메시지가 성공적으로 전송되었습니다.`);
        })
        .catch((error) => {
          log(`${phoneNumber}로 알림 메시지 전송 실패: ${error.message}`, error);
        });
    });
  } catch (error) {
    log('Error fetching public IP:', error);
  }
}

 

6.정상적으로 메세지 수신 테스트완료

'Node' 카테고리의 다른 글

Winston 모듈  (0) 2023.12.22
Path모듈  (0) 2023.12.21
util 모듈 - promisify()  (0) 2023.12.21
mysql 연동 시 datetime 에러  (0) 2023.12.19
Connection과 Connection Pool  (0) 2023.12.19