0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Reactを使ってブログサイトを作る 03 - リクエストモジュールのカプセル化

Last updated at Posted at 2024-12-30

背景

  • プロジェクト全体で多くのネットワークリクエストを送信する必要があるため、axiosというサードパーティライブラリを使用してリクエストを統一的にカプセル化し、管理と再利用を容易にします。
  1. ほとんどのAPIは同じベースURLを使用しています。
  2. ほとんどのAPIは同じタイムアウト時間を設定する必要があります。
  3. ほとんどのAPIはTokenを使用した権限処理が必要です。

インストール

  • 以下のコマンドを実行してaxiosをインストールします:
npm i axios

実装

  1. utils/request.js ファイルを作成

    • axiosのインスタンスを作成し、baseURL、リクエストインターセプター、レスポンスインターセプターを設定します。
      image.png
  2. utils/index.js にて統一的にrequestをエクスポート

    • 他の場所で使用する際には、直接以下のようにインポートします:
    import { request } from '@/utils';
    

image.png


0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?