개발하는 루루언니

React : api key 이용방법과 사용방법 본문

컴퓨터 정보/리액트

React : api key 이용방법과 사용방법

혜닝혜루 2023. 1. 6. 20:20
728x90
반응형

 

리액트 api 키

 

 

리액트에서 api키를 가져와 사용하는 방법이다.

 

1. 최상단에 .env 라는 파일을 만들어 키명(동일) 과 api키를 넣어준다.

✔앞에 꼭 REACT _APP 이라는 키명을 넣어야 한다 > 리액트에서 그렇게 하라고함/ 공백도 없어야한다

 

 

2. .env 파일은 퍼블릭한 파일이므로 깃허브에는 올리면 안된다.

 

✔ gitignore 파일에 .env 파일을 적어주면 깃허브 파일에 올릴때 올라가지 않는다.

 

 

3. 키를 가져와 사용하고 싶다면 아래와 같이 입력하면 된다.

✔ process.env.리액트 키 를 입력하고 변수  API_KEY에 넣어주면된다.

4. 변수에 젖아한  api키를 사용해보자

✔ <<api_key>>  라는 곳에 ${API_KEY} 를 입력해준다.

콘솔창으로 확인해 봤을때 200으로 정상적으로 데이터를 받아온걸 확인할 수 있다.

 

우리가 axios를 쓸때 항상 data라는 필드 안에 받은 응답을 넣어준다.
더이상 awite json 해서 가져올 필요가 없이 axios로 한번에 data를 받아올 수 있는것이다.

 

 

 

 

데이터를  요청과 응답 에러 확인하는 방법은 아래에 참조를 해놓겠다. 

api.interceptors.request.use(function (config) {
  // Do something before request is sent
  console.log("보냄",config)
  return config;
}, function (error) {
  // Do something with request error
  console.log("요청 에러",error)
  return Promise.reject(error);
});

// Add a response interceptor
api.interceptors.response.use(function (response) {
  // Any status code that lie within the range of 2xx cause this function to trigger
  // Do something with response data
  console.log("어떤 데이터니?",response)
  return response;
}, function (error) {
  // Any status codes that falls outside the range of 2xx cause this function to trigger
  // Do something with response error
  console.log("받은 데이터 에러뭐야?",error)
  return Promise.reject(error);
});

export default api;
728x90