LoginSignup
23

More than 3 years have passed since last update.

【Nuxt.js】axiosでheaderにAuthorizationを常につけたい!

Last updated at Posted at 2020-04-20

投稿者のお悩み

・JWT認証のアプリでaxiosでAPI叩くときにheadersにAuthorization:tokenをくっつける共通処理を作りたい
(色んな記事みたけどうまくいかないよ・・・)

お悩み解決

nuxtのpluginsを使ってaxiosをラップする処理を用意する

①plugins配下にaxios.jsを作成して、共通処理を書く

plugins/axios.js
import axios from 'axios'

export default function({ $axios }) {
  $axios.onRequest((config) => {
    axios.defaults.headers.common['Authorization'] = localStorage.getItem(
      'auth._token.local'
    )
    return config
  })
}
// axiosにデフォルトでヘッダーにAuthorizationを用意し、中身はlogalStorageのtokenを貼り付けるよ
// onRequest リクエスト飛ばす前に処理いれるよ
// common はすべてのリクエストGET,POST....につけるよ

無題.png
https://github.com/axios/axios
読者の声:おい!公式にその通り書いてあるぞ!この程度で記事にすんなや!
投稿者:ひぃ

②nuxt.config.jsでplugins/axios.jsを認識させる

nuxt.config.js
// ~~ 省略 ~~

plugins: ['@/plugins/axios']
// pluginsフォルダ配下のaxiosを認識するよ

// ~~ 省略 ~~

いたってシンプル、これだけ!!!落ち着いて公式を読もうね。

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
23