28
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

axiosのヘッダーにJSON Web Tokenを埋める

Last updated at Posted at 2017-10-28

JSON Web Token を毎回ヘッダに埋めるのが嫌だったのでつくってみました。

http.js
import axios from 'axios'

const http = axios.create({
  baseURL: `${process.env.API_URL}/api/v1/`
})
http.interceptors.request.use((config) => {
  if (token) {  
    config.headers.Authorization = `Bearer ${token}`
    return config
  }
  return config
}, function (error) {
  return Promise.reject(error)
})

http.post('/hogehoge')

http.interceptors.request.use で、リクエストを投げる前にインターセプトしてリクエストヘッダにアクセスできるので、それを利用します。
Token を Cookie やローカルストレージなど、環境に合わせて取得し、それを Authorization : Bearer token の形になるように埋めています。
あとはそのインスタンスを使い回すだけ、最高。

28
32
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
28
32

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?