GITHUB
Axios 정리하기
BLOGProject
Seohyun
Develop
10 Jun 2023
Axios 정리하기

Request

문법

axios.get(url); // axios(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 {
// axios.get(), axios.post(),axios.put(), axios.delete()
const response = await axios(url);
console.log(response);
} catch (error) {
console.log(error.response);
}
};

Headers

axios.get에 headers 추가

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에 headers 추가

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);
};

결과

post_headers_ex_result



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
request.headers["Accept"] = `application/json`;
console.log("요청 보냄");
return request;
},
(error) => {
if (error.response.status === 404) {
return Promise.reject(error);
}
);
// headers
if (error.response.status === 404) {
  • 요청 예시 코드입니다.
  • 응답 예시 코드입니다.

© 2024 Park Seohyun