LoginSignup
73
70

More than 5 years have passed since last update.

axiosでBearerトークンを簡単に設定したい。

Posted at

小ネタです。

AxiosはBearer認証がめんどくさい

axios でAPIを呼ぶときの認証にBearerトークンを指定する場合、下のような書き方をすると思いますが、

axios.get('https://api.example.com/api/v1/foo', {
  headers: {
    Authorization: `Bearer ${token}`,
  }
})

毎回こう書くのは面倒くさい。

Basicであれば認証なら

axios.get('https://api.example.com/api/v1/foo', {
  auth: { username: user, password: pass }
})

と書けるのだから、

axios.get('https://api.example.com/api/v1/foo', {
  auth: token
})

と書きたいわけですよ。
auth が文字列の場合はBearer認証、オブジェクトの場合はBasic認証とする。)

axios のミドルウェアを書いて解決する

そう思う人は他にもいるみたいでPRまで上がっているのですが、これ以上複雑にしたくないということであっさり却下されてしまっています。

でも、なんとかしたい。そこで axios-middleware の登場です。

名前の通り aixos のミドルウェアを作るためのモジュールで、リクエスト前、リクエスト後に自前のフィルタを挟むことができるようになります。

これでリクエスト前のパラメータを修正して、 auth が文字列の場合は、Authorization: Bearer ヘッダに変換して差し込めばやりたいことが実現できますね。

import axios from 'axios'

import { Service } from 'axios-middleware'
const service = new Service(axios)

service.register({
  onRequest(config) {
    if(typeof config.auth == 'string'){
      config.headers['Authorization'] = `Bearer ${config.auth}`
      delete config.auth
    }

    return config
  }
})

自分がよく使うヘッダ指定やデータ変換を登録しておくと axios の使い勝手が更に向上しますね。

73
70
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
73
70