🅰️
Axiosの概要
Axiosとは
AxiosはTypeScriptやJavaScriptで使えるHTTPクライアントライブラリです。
PromiseベースのAPIを提供しており非同期処理が扱いやすく、JSONデータの自動変換も行ってくれるため、レスポンスデータの処理がしやすくなっています。
インストール方法
まずはAxiosをプロジェクトにインストールします。
npm install axios
# または
yarn add axios
基本的な使い方
Axiosを使うと、シンプルにHTTPリクエストを送ることができます。
GETリクエスト
import axios from "axios";
axios.get("https://jsonplaceholder.typicode.com/posts/1")
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
response.data にサーバーから返却されたデータが入っています。
async/awaitを使った書き方
Promiseチェーンよりも可読性が高くなるため、こちらが推奨されることが多いです。
import axios from "axios";
async function fetchPost() {
try {
const response = await axios.get("https://jsonplaceholder.typicode.com/posts/1");
console.log(response.data);
} catch (error) {
console.error(error);
}
}
fetchPost();
POSTリクエスト
データを送信するときも簡単に書けます。
const newPost = {
title: "Axios学習",
body: "Axiosテスト",
userId: 1,
};
axios.post("https://jsonplaceholder.typicode.com/posts", newPost)
.then(response => {
console.log(response.data);
});
よく使う便利機能
共通設定(ベースURL・ヘッダー)
同じAPIサーバーに複数回リクエストする場合は、インスタンスを作って共通設定をまとめるのが便利です。
const api = axios.create({
baseURL: "https://jsonplaceholder.typicode.com",
headers: {
"Content-Type": "application/json",
},
});
api.get("/posts").then(res => console.log(res.data));
リクエスト・レスポンスのインターセプター
API呼び出し前後に処理を挟むことができます。ログ出力や認証トークンの付与に便利です。
api.interceptors.request.use(config => {
console.log("リクエスト: ", config.url);
return config;
});
api.interceptors.response.use(response => {
console.log("レスポンス: ", response.status);
return response;
});
まとめ
- AxiosはPromiseベースで非同期処理が扱いやすい
- JSONの変換が自動で行われるのでレスポンス処理が楽
- GET/POSTなど基本操作はシンプル
- 共通設定やインターセプターを使うと大規模開発にも対応できる
Discussion