1️⃣ Axios란?
자바스크립트에서 HTTP 통신을 쉽게 처리할 수 있도록 만든 HTTP 비동기 통신 라이브러리입니다. 쉽게 말해 백엔드와 프론트엔드가 쉽게 통신을 하기 위해 Ajax와 더불어 사용됩니다. 이미 자바스크립트에는 fetch api가 있지만, 보통 프레임워크에서 ajax를 구현할 땐 axios를 씁니다. ( fetch와의 차이점을 아래에서 더 알아보겠습니다. )
Node.js 와 브라우저에서도 사용할 수 있습니다. Axios에는 많은 기능들이 있어서, 쉽고 편리하게 데이터를 가져올 수 있어서 개발자들이 많이 사용하는 방법입니다.
2️⃣ Axios 특징
- Promise(ES6) API 사용
- 요청과 응답 데이터의 변형
- HTTP 요청 취소
- HTTP 요청과 응답을 JSON 형태로 자동 변경
3️⃣ Axios 설치하기
리액트에서 새 터미널을 열어 npm을 이용해 설치합니다.
npm i axios
4️⃣ Axios 사용법
먼저 import 해주는 것을 잊지말자!
import axios from 'axios';
get 호출
✔ 단순 데이터 (페이지 요청, 지정된 요청) 요청을 수행할 경우
// user에게 할당된 id 값과 함께 요청을 합니다.
axios.get('/user?ID=12345') // 예시 : 'http://localhost:8082/test'
// 아무것도 적지 않으면 -> http://localhost:3000/test
// 성공한 경우
.then(function (response) {
console.log(response);
})
// 에러난 경우
.catch(function (error) {
console.log(error);
})
// 항상 실행되는 함수
.finally(function () {
});
✔ 파라미터 데이터를 포함시키는 경우 ( ex. 사용자 번호에 따른 조회 )
axios.get('/user', { // 예시 : 'http://localhost:8082/test'
// 아무것도 적지 않으면 -> http://localhost:3000/test
// 파라미터 데이터 포함
params: {
ID: 12345 // key-value
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
.finally(function () {
});
POST 호출
post 메서드에서는 일반적으로 데이터를 Message Body에 포함시켜 보낸다.
GET 메서드의 params를 사용한 경우와 비슷하게 수행된다.
axios.post("url", {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
}).catch(function (error) {
})
출처: https://inpa.tistory.com/entry/AXIOS-📚-설치-사용#axios_특징 [Inpa Dev 👨💻:티스토리]
DELETE
delete 메서드에는 일반적으로 BODY가 비어있다.
axios.delete('/user?ID=12345')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
PUT
데이터베이스에 저장되어 있는 내용을 수정(갱신)
put 메서드는 서버 내부적으로 get → post 과정을 거치기 때문에 post 메서드와 비슷한 형태이다.
axios.post("url", {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
}).catch(function (error) {
})
출처 https://inpa.tistory.com/entry/AXIOS-📚-설치-사용#axios_특징
5️⃣ 실습
스프링부트와 리액트를 사용해 실제로 서버 통신을 해보자!
✔ React
- 터미널에 npm i axios
하여 axios 설치
- import axios from 'axios';
리액트의 App.js 파일에 import해주기
- <button onClick={a}>클릭</button>
리턴문 안에 버튼 만들고, onClick 이벤트 추가 ⇒ 이후 a라는 함수 만들기
return (
<div className="App">
<button onClick={a}>클릭</button>
</div>
);
- a 함수 안에 axios 문법으로 get 호출 작성
let a = () => {
axios.get('',{
params:{
name: "이름" // key-value
}
})
}
let a = () => {
axios.get('http://localhost:8082/test', { // 아무것도 적지 않으면 -> http://localhost:3000/test
params:{
name: "이름" // key-value
}
}).then((res) => { // 성공했을 시
console.log(res);
});
}
✔ SpringBoot
- 스프링부트에 TestContoller.java 생성
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@GetMapping("/test")
public String test() {
return null;
}
}
- 받는 파라미터의 변수 이름과 리액트에서 요청 시 보내는 key의 이름이 동일 해야함
✔ 실행 결과
'Project 댕린이집' 카테고리의 다른 글
[React] React-Router-Dom (0) | 2024.01.17 |
---|---|
CORS 트러블슈팅 (0) | 2024.01.12 |
React 연습 (0) | 2024.01.06 |
React의 state를 알아보자 (0) | 2024.01.05 |
JSX 문법 (1) | 2024.01.03 |