Nuxt.js: use axios interceptors in plugins

Created on 3 Jul 2017  路  2Comments  路  Source: nuxt/nuxt.js

version : 1.0.0-alpha.4

import axios from 'axios';

export default ({ store, app: { router }, req }) => {
  // I just want to send an HTTP request to bring Token
  axios.interceptors.request.use(function (config) {
    console.log("store Token : ",store.state.token);
    config.headers.token = store.state.token || "";
    return config
  });
};
async nuxtServerInit({ commit, dispatch, rootState }, { req }) {
    if (req.headers.cookie) {
      let cookies = req.headers.cookie.split(";"), arr;
      for (var i = 0, len = cookies.length; i < len; i++) {
        arr = cookies[i].split("=");
        if (_.trim(arr[0]) == "token") {
         // here is the only place to set Token
          await commit("SET_TOKEN", arr[1]);
          await dispatch("getUserInfo");
        }
      }
    }
  },
 async getUserInfo({ commit }) {
    let { ok, data: { userInfo, authToken } } = await axios("/api/auth/info", {}, "GET");
    ...
    ...
  },
 SET_TOKEN(state, token) {
    state.token = _.trim(token);
  },

first log :
image

second log :
image

This question is available on Nuxt.js community (#c877)

Most helpful comment

@SzHeJason Stateful axios instance should not be shared across SSR requests. Please use axios module for best experience and then you can use app.$axios in your plugins setting token. (Bounes it also has setToken helper :) )

All 2 comments

@SzHeJason Stateful axios instance should not be shared across SSR requests. Please use axios module for best experience and then you can use app.$axios in your plugins setting token. (Bounes it also has setToken helper :) )

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

maicong picture maicong  路  3Comments

vadimsg picture vadimsg  路  3Comments

mikekidder picture mikekidder  路  3Comments

uptownhr picture uptownhr  路  3Comments

mattdharmon picture mattdharmon  路  3Comments