LoginSignup
5
9

More than 3 years have passed since last update.

Vue.js + axios でヘッダーにログイン情報を毎回セットする。

Last updated at Posted at 2019-11-11

plugin を自作して axios の create() と interceptors() を使ってラップした http plugin を作ると良いかもしれません。

src/plugins/http.ts
import _Vue from 'vue';
import axios from 'axios';

export default {
  install(Vue: typeof _Vue): void {
    const http = axios.create({
      // URL は環境変数とかで変えられるにする
      baseURL: 'http://localhost:3000/',
      timeout: 10000,
    });
    http.interceptors.request.use((config: any) => {
      // $stores.auth.show に認証情報が入っているとする
      config.headers = Vue.prototype.$stores.auth.show;
      return config;
    });
    Vue.prototype.$http = http;
  },
};

Typescript で書いているため、上記 plugin の型ファイルを *.d.ts という拡張子にしてどこかに置きます。

src/types/http.d.ts
import Vue from 'vue';
import { AxiosStatic } from 'axios';

declare module 'vue/types/vue' {
  interface Vue {
    $http: AxiosStatic;
  }
}

あとは main.ts のどこかに下記を書きます。
すると、自作 plugin が使えるようになります。

src/main.ts
// 略

import http from '@/plugins/http';
Vue.use(http);

認証情報の store はこんなイメージです。
vuex-module-decorators を使っています。

src/stores/AuthStore.ts
import Vue from 'vue';
import { Module, Mutation, VuexModule } from 'vuex-module-decorators';
import LoginInterface from '@/interfaces/LoginInterface';
import { AuthStoreInterface } from '@/interfaces/StoresInterface';
import { AuthResponseInterface, ErrorResponseInterface } from '@/interfaces/ResponseInterface';

@Module({ name: 'auth' })
export default class AuthStore extends VuexModule implements AuthStoreInterface {
  public token = '';
  public user_id  = 0;

  public get show(): object {
    return {
      Authorization: `Token ${this.token}`,
      'User-Id': this.user_id,
    };
  }

  @Action
  public create(users: LoginInterface): void {
    Vue.prototype.$http.post('/users/auth', { user: users })
    .then((res: AuthResponseInterface): void => {
      this.set_token(res.data.token);
      this.set_user_id(res.data.id);
    })
    .catch((err: ErrorResponseInterface): void => {
      // エラー処理
    });
  }

  @Mutation
  private set_token(token: string): void {
   this.token = token;
  }

  @Mutation
  private set_user_id(user_id: number): void {
    this.user_id = user_id;
  }
}

そうすると Store 内でVue.prototype.$http.get()Vue.prototype.$http.post()すると AuthStore のログイン情報を毎回見に行ってくれます。
vue ファイルから呼び出す際は this.$http.get()this.$http.post()でリクエストできます。

もし vuex-persist を使っていれば、リロードしても消えません。

5
9
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
5
9