[WEB] axios 문법 정리

서주·2023년 11월 10일
post-thumbnail

axios 비동기 통신 라이브러리

아래는 내가 사용했던 코드

axios({
        method: 'post',
        url: `${apiUrl}/api/shot/modify`,
        headers: {
            'Authorization': `${user.jwtToken}`
        },
        data: {
            date : route.params.date,
            shots: JSON.stringify(finalShots.current),
            feedback: JSON.stringify(finalFeedback.current),
            shot_count : finalShots.current.length,
            target_count : finalShots.current.filter((shot) => (shot >= 4 && shot <= 12) || shot == 17).length,
        }
    }).then(response => {
        console.log("Data sent successfully:", response.data);
        initialShots.current = finalShots.current;
        initialFeedback.current = finalFeedback.current;
    }).catch(error => {
        console.error("Error sending data:", error);
    });

headers로 jwt전달하고 data에 전달 내용 적음.

사용하지는 않았는데
params : URL파라미터(?key=value로 요청하는 url get방식을 객체로 표현한 것)
responseType : 서버가 응답해주는 데이터의 타입 지정 (arraybuffer, documetn, json, text, stream, blob)

다른 블로그의 axios 예시

/* axios 파라미터 문법 예시 */

axios({
    method: "get", // 통신 방식
    url: "www.naver.com", // 서버
    headers: {'X-Requested-With': 'XMLHttpRequest'} // 요청 헤더 설정
    params: { api_key: "1234", langualge: "en" }, // ?파라미터를 전달
    responseType: 'json', // default
    
    maxContentLength: 2000, // http 응답 내용의 max 사이즈
    validateStatus: function (status) {
      return status >= 200 && status < 300; // default
    }, // HTTP응답 상태 코드에 대해 promise의 반환 값이 resolve 또는 reject 할지 지정
    proxy: {
      host: '127.0.0.1',
      port: 9000,
      auth: {
        username: 'mikeymike',
        password: 'rapunz3l'
      }
    }, // proxy서버의 hostname과 port를 정의
    maxRedirects: 5, // node.js에서 사용되는 리다이렉트 최대치를 지정
    httpsAgent: new https.Agent({ keepAlive: true }), // node.js에서 https를 요청을 할때 사용자 정의 agent를 정의
})
.then(function (response) {
    // response Action
});

여기 참고함

0개의 댓글