React App에서 Azure Central API 사용하기

이경은·2022년 1월 3일
1

1. '.env' 파일 설정

설정 값

  • Host API 설정
  • Authorization 설정

주의 사항

  • 변수명에 REACT_APP은 반드시 들어가야 함.

2. apiConfig 파일 작성

  • axios는 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리.
  • fetch를 이용해도 상관은 없음. 둘의 차이점은 링크 참조
import axios from 'axios';
  • .env에서 설정한 api와 token 선언.
const apiEndpoint = process.env.REACT_APP_FUNCTION_CENTRAL_ENDPOINT;
const apiToken = process.env.REACT_APP_FUNCTION_CENTRAL_TOKEN;
  • API 사용해서 값을 불러오는 함수 작성
const getMonitorData = async (param) => {
    const config = {
        method: 'GET',
        data: JSON.stringify(param),
        headers: {
            Authorization: apiToken // 인증을 위한 토큰 키. Header에 들어가야 함
        },
        // central에서 만들어둔 function. 뒤에 api-version은 필수
        url: `${apiEndpoint}/devices/w5100s-evb-pico-02/telemetry/${param}?api-version=1.0`  
    };

    try {
        const { data } = await axios(config);
        console.log('get monitor data');
        return data;
    } catch (error) {
        console.log(error);
        return false;
    }
};
profile
Web Developer

0개의 댓글