Nodejs
[Node.js] axios 활용해서 비동기로 http 통신하기
teamnova
2023. 10. 8. 12:00
728x90
axios 란
브라우저나 node.js에서 비동기로 http 통신을 하기 위한 도구입니다.
비슷한 라이브러리로 reqeust 등이 있습니다. promise 용법을 사용 가능합니다.
패키지 다운로드 방법은
npm install axios
를 사용하면 할 수 있습니다.
get과 post방식이 있습니다.
1.get방식
const axios = require('axios')
axios({
method : 'get',
url : 'https://www.naver.com/'
}).then((res)=>{
console.log(res)
})
네이버로 응답값을 받아보겠습니다.

const axios = require('axios')
axios({
method : 'get',
url : 'http://rembridge.shop/api/user/test' // url을 변경해서 테스트해주세요
}).then((res)=>{
console.log(res)
})
요청할 url을 입력하고 그대로 응답을 받아봅니다.

특정값만 출력하고싶으면 다음과같이 추출할 수 있습니다.
const axios = require('axios');
axios({
method: 'get',
url: 'http://rembridge.shop/api/user/test' // url을 변경해서 테스트해주세요
})
.then((res) => {
const test = res.data.message; // 원하는 응답값 추출하기
console.log(test);
})

2.post방식
const axios = require('axios')
axios.post('http://localhost:3000/axios',{
name : 'balmostory'
}).then((res)=>{
console.log(res)
})
post방식은 url을 쓰고 보낼 데이터를 {}안에 json형식으로 넣어주시면 됩니다.
이상으로 axios 활용해서 비동기로 http 통신하는 방법이었습니다!