작업 상태

- SSR 작업 중 https로 데이터를 얻어오는 일이 있어서 axios쪽에 https 인증 무시를 설정한 후 브라우저에서 계속 보였습니다.
 
에러 메시지 

 

Uncaught TypeError: https.Agent is not a constructor 

Uncaught TypeError: https.Agent is not a constructor
이미지를 설명하는중@.@

const agent = new https.Agent({    //<-- 에러 발생 부분
  rejectUnauthorized: false
});

//서버와 통신하다: communicate with the server
const cwts = axios.create({
  baseURL: `${apiUrl}/api`,
  timeout: 5000,
  httpsAgent: agent,
  headers: {
    'Content-Type': 'application/json',
  },
});

- 코드는 특별히 문제가 없었습니다.

- https.Agent는 HTTP(S) 연결을 관리하고 재사용하는 HTTP(S) 에이전트 객체의 인스턴스를 생성하는 생성자 함수입니다. 일반적으로 Node.js에서 HTTPS 서버에 요청을 보낼 때 사용됩니다.

 

원인

- 원인은 이 부분의 코드가 문제가 아니었습니다.

- 상단 코드가 server용, client용 공용 util으로 사용되는 부분이어서 문제가 되는것이었습니다.

- 변환, 배포후 server용은 node에서 동작 client용은 브라우저에서 동작하게 되는 부분입니다.

- 이 부분에서 https.Agent가 브라우저에서 동작하면서 발생하는 문제였습니다.

처리

- 개발환경이 vite, react tsx,ssr 작업 중이어서 vite환경변수를 이용해서 설정을 분리했습니다.

const ssr :boolean = import.meta.env.SSR;

let configx = {
  baseURL: `${apiUrl}/api`,
  timeout: 1000*10,
  // httpsAgent: agent,
  headers: {
    'Content-Type': 'application/json',
  },
}

if( ssr ){//is server
  const agent = new https.Agent({  
    rejectUnauthorized: false
  });

  configx = Object.assign({}, configx, { httpsAgent: agent });
}
 
const cwts = axios.create(configx);

클라이언트 측 변환코드

let configx = {
  baseURL: `${apiUrl}/api`,
  timeout: 1e3 * 10,
  // httpsAgent: agent,
  headers: {
    "Content-Type": "application/json"
  }
};
const cwts$1 = axios$1.create(configx);

서버측 변환코드

let configx = {
  baseURL: `${apiUrl}/api`,
  timeout: 1e3 * 10,
  // httpsAgent: agent,
  headers: {
    "Content-Type": "application/json"
  }
};
{
  const agent = new https.Agent({
    rejectUnauthorized: false
  });
  configx = Object.assign({}, configx, { httpsAgent: agent });
}
const cwts$1 = axios.create(configx);

 

참고

시작하기 | Vite (vitejs-kr.github.io)  vite

작업 상태

- 기존에 react에서 사용하던 코드를 vite사용 환경으로 포팅하던중 .env 에서 설정한 변수 사용중 발생했습니다.

- react만 사용할때는 정상 작동했던 코드입니다.

 

.env

REACT_APP_LOG_LEVEL=debug

  

const apiLogLevel = process.env.REACT_APP_LOG_LEVEL; //에러가 발생한 장소 입니다


에러 메시지 

Uncaught ReferenceError: process is not defined


원인

- vite 쪽 환경으로 이동하면서 발생한 문제였습니다.

처리

-  vite 에서 환경변수 관리하는 형태로 변경합니다.

- vite 쪽에서 VITE_ prefix 사용을 권장합니다.

const apiLogLevel = import.meta.env.VITE_APP_LOG_LEVEL;

 

.env

VITE_APP_LOG_LEVEL=debug

 

또는

npm install dotenv 이후 

import dotenv from 'dotenv';
dotenv.config();

로 하면 동작하기는 합니다.

 


참고

--------------------------React

React에서 .env 환경 변수를 사용하기 위해서는 몇 가지 조건이 있습니다.

환경 변수 이름은 반드시 REACT_APP_으로 시작해야 합니다.
환경 변수는 프로젝트 루트 디렉토리에 위치한 .env 파일에 선언해야 합니다.
위 두 가지 조건을 만족하면, React 애플리케이션에서 process.env.REACT_APP_ 접두어를 사용하여 .env 파일에 선언된 환경 변수에 접근할 수 있습니다.

 

.env 파일명 

<projectroot>/.env
REACT_APP_LOG_LEVEL=debug

 

react.js에서 사용예시

const apiLogLevel = process.env.REACT_APP_LOG_LEVEL;

 

--------------------------Vite

Vite에서 .env 환경 변수를 사용하기 위해서는 다음과 같은 방법을 사용할 수 있습니다.

.env 파일을 프로젝트 루트 디렉토리에 위치시킵니다.
.env 파일에서 사용할 환경 변수를 선언합니다. 변수 이름은 VITE_으로 시작해야 합니다.

 

/.env
VITE_APP_LOG_LEVEL=debug

 

vite 환경에서 사용예시

const apiUrl = import.meta.env.VITE_APP_LOG_LEVEL;

 

주의할점은, Vite에서는 .env.local, .env.development, .env.production과 같은 환경 변수 파일도 지원합니다. 이러한 파일을 사용하면, 개발 환경과 프로덕션 환경에서 각각 다른 환경 변수 값을 설정할 수 있습니다.

 

보통은 참조할점인데. react에서 이동하는 상황이어서  .env, .env.development, .env.production 이 세개의 파일이 존재했는데, vite에서는 설정값에 따라 알아서 다른 환경변수 파일을 불러옵니다.

 

Vite의 환경 변수와 모드 | Vite (vitejs-kr.github.io)

 

Vite

Vite, 차세대 프런트엔드 개발 툴

vitejs-kr.github.io

 

+ Recent posts