fetch()보다 간결하고 직관적인 문법 제공npm install axios
💡 설치 전 React 서버를 종료하고, 최상위 폴더에서 설치하는 것이 좋음
import axios from 'axios';
const response = await axios.get("https://jsonplaceholder.typicode.com/posts");
console.log(response.data); // 실제 데이터
console.log(response.status); // HTTP 상태 코드
const response = await axios.get("https://jsonplaceholder.typicode.com/comments?postId=1");
const obj = { title: "test", body: "testContent", userId: 1 };
const response = await axios.post("https://jsonplaceholder.typicode.com/posts", obj);
const obj = { id: 1, title: "updated", body: "updatedContent", userId: 1 };
const response = await axios.put("https://jsonplaceholder.typicode.com/posts/1", obj);
const response = await axios.delete("https://jsonplaceholder.typicode.com/posts/1");
import axios from 'axios';
import { useState } from 'react';
export default function AxiosExample() {
const [count, setCount] = useState(0);
const onAxiosGet = async () => {
const response = await axios.get("https://jsonplaceholder.typicode.com/posts");
console.log(response);
};
const onAxiosPost = async () => {
const obj = { title: "test", body: "testContent", userId: 1 };
const response = await axios.post("https://jsonplaceholder.typicode.com/posts", obj);
console.log(response);
};
const onAxiosPut = async () => {
const obj = { id: 1, title: "updated", body: "updatedContent", userId: 1 };
const response = await axios.put("https://jsonplaceholder.typicode.com/posts/1", obj);
console.log(response);
};
const onAxiosDelete = async () => {
const response = await axios.delete("https://jsonplaceholder.typicode.com/posts/1");
console.log(response);
};
return (
<>
<h2>Axios 예제</h2>
<button onClick={onAxiosGet}>GET 요청</button>
<button onClick={onAxiosPost}>POST 요청</button>
<button onClick={onAxiosPut}>PUT 요청</button>
<button onClick={onAxiosDelete}>DELETE 요청</button>
</>
);
}
Access to XMLHttpRequest at 'http://localhost:8080/board' from origin 'http://localhost:5173' has been blocked by CORS policy
@CrossOrigin(value = "http://localhost:5173")
@RestController
public class BoardController {
// ...
}
💡 CORS(Cross-Origin Resource Sharing)는 서로 다른 서버 간의 요청/응답을 허용하기 위한 정책입니다.