Request
문법
axios.get(url);
axios.post(url);
axios.patch(url);
axios.put(url);
axios.delete(url);
- promise로 반환합니다.
- data는 response의 data 속성에 있습니다.
- error는
error.response에 있습니다.
예시
import axios from "axios";
const fetchData = async () => {
try {
const response = await axios(url);
console.log(response);
} catch (error) {
console.log(error.response);
}
};
axios.get(url, { headers });
axios.get(주소, {
headers: {
추가할헤더키: "값",
},
});
- 두 번째의 argument에 headers를 사용합니다.
예시
const url = "https://jsonplaceholder.typicode.com/posts/1";
const Headers = () => {
const [data, setData] = useState("");
const fetchData = async () => {
try {
const { data } = await axios(url, {
headers: {
Accept: "application/json",
},
});
setData(data.title);
} catch (error) {
console.log(error.response);
}
};
};
axios.post(url, { data }, { headers });
axios.post(
주소,
{
보낼데이터: "데이터값",
},
{
headers: {
추가할헤더키: "값",
},
}
);
- 데이터가 있는 요청의 경우 세 번째 argument에 추가할 headers를 넣어 사용합니다.
예시
const url = "https://jsonplaceholder.typicode.com/posts";
const [data, setData] = useState("");
const handleSubmit = async (e) => {
e.preventDefault();
try {
const resp = await axios.post(url, { body: data });
console.log(resp, "resp");
} catch (error) {}
console.log(data);
};
결과

Global Defaults
axios.defaults.headers["Accept"] = "application/json";
axios.defaults.baseURL = "https://api.example.com";
axios.defaults.headers["Authorization"] = AUTH_TOKEN;
axios.defaults.headers.post["Content-Type"] =
"application/x-www-form-urlencoded";
- 모든 axios 요청의 설정에 default 값을 전역으로 명시할 수 있습니다.
- 주로 요청에서 headers를 명시하는 데에 쓰입니다.
Custom Instance
- 커스텀 속성을 지닌 인스턴스를 생성할 수 있습니다.
authFetch.interceptors.request.use(
request.headers["Accept"] = `application/json`;
if (error.response.status === 404) {
return Promise.reject(error);
if (error.response.status === 404) {