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?

axios interceptors

Posted at

axios interceptorsを使う

axiosでAPIを呼び出すときにaxios interceptorsを使用するようにしました。

axios interceptorsを使うと、呼び出しの時にトークンのチェックができたり、共通化ができることで後の修正がしやすいと感じました。

Utils.js
import axios from 'axios'
import Constants from './Constants'
import { checkTokenExpiration } from './Cognito'
import store from '@/store'

const axiosInstance = axios.create({
    baseURL: Constants.BASE_URL,
    timeout: Constants.TIMEOUT_NORMAL,
})

axiosInstance.interceptors.request.use(
    async (config) => {
        const exp = store.state.auth.idToken.payload.exp
        const now = Date.now() / 1000

        // トークンの有効期限が5分以内に切れる場合にリフレッシュ
        if (exp && exp - Constants.TOKEN_REFRESH_TIME <= now) {
            await checkTokenExpiration()
        }

        // リフレッシュ後のトークンを使用してヘッダーを設定
        if (store.state.auth.idToken.jwtToken) {
            config.headers.authorization = store.state.auth.idToken.jwtToken
        }

        return config
    },
    (error) => Promise.reject(error),
)

axios.interceptors.response.use(
    (response) => response,
    async function (error) {
        return Promise.reject(error)
    },
)

export default {
    axiosInstance,
}

呼び出し側

call.js
const response = await Utils.axiosInstance.get(`/api/?path=${path}`, {
    headers: { 'Content-Type': 'application/json' },
})
console.log("response", response)
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?