Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
20
Help us understand the problem. What is going on with this article?
@masatakaaaa

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

More than 1 year has passed since last update.

投稿者のお悩み

・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を認識するよ

// ~~ 省略 ~~

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

20
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
20
Help us understand the problem. What is going on with this article?