@nuxtjs/axios

plugins -> axios.js

import md5 from 'js-md5'
import Cookies from 'js-cookie';
import axios from 'axios';

export default function ({ $axios, redirect, store }) {
    $axios.onRequest(config => {
        let time = parseInt(new Date().getTime()/1000);
        let secret = 'jTJxKcGL';
        let appId = 'guard';
        let sign = md5(`appId=${appId}&time=${time}${secret}`);
        let access_token = Cookies.get('session');
        try {
          if(!access_token && axios.defaults.cookies.session) {
              access_token = axios.defaults.cookies.session;
          }
        } catch (error) {
          
        }
        if(config.url.indexOf('?') > -1){
            config.url = `${config.url}&time=${time}&sign=${sign}&appId=${appId}`;
        }else{
            config.url = `${config.url}?time=${time}&sign=${sign}&appId=${appId}`;
        }
        if(access_token){
            config.url = `${config.url}&access-token=${access_token}`;
        }
        return config;
    })


    $axios.onResponse(response => {
        //response.data.errCode是接口返回的值,如果值为401,登录过期,然后跳转到登录页,
        if(response.data.code == 401) { 
            store.commit('handleIsLogin', true)
        }
        return response
    })


    $axios.onError(error => {
      const code = parseInt(error.response && error.response.status)
      if (code === 400) {
        redirect('/400')
      }
    })
  }

middleware -> header.js


import axios from 'axios'
export default function({req,res}) {
    var cookies = {};
    try {
        req.headers && req.headers.cookie.split(';').forEach(function(cookie) {
            var parts = cookie.match(/(.*?)=(.*)$/)
            cookies[ parts[1].trim() ] = (parts[2] || '').trim();
        });
        axios.defaults.cookies = cookies;
        return cookies;
    } catch (error) {
        
    }
}

store -> index.js

import {api} from './api'
import Vuex from 'vuex'
import Cookies from 'js-cookie'

const createStore = () => {
  return new Vuex.Store({
    strict: false,
    state: () => ({
        isLogin: false
    }),
    mutations: {
        //是否登录
        handleIsLogin (state, data) {
            state.isLogin = data;
        },

        logout (state, vm) {
            Cookies.remove('user');
            Cookies.remove('session');
            localStorage.clear();
            location.reload();
        },
    },
    actions: api
  })
}

export default createStore

store -> api.js

  1. $post(url, params)
  2. $get(url, {params: params})
export const api = {

  //首页登录
  async getUserLogin ({ commit }, params) {
    return await this.$axios.$post('api/v1/site/login', params)
  },

  //退出登录
  async userLogout ({ commit }, params) {
    return await this.$axios.$post('api/v1/site/logout', params)
  },

  //kol
  async xiaohongshuKol ({ commit }, params) {
    return await this.$axios.$get('api/v1/kol', {params: params})
  },

  //kol - 收藏 || 取消收藏
  async kolCollect ({ commit }, params) {
    return await this.$axios.$get('api/v1/kol/favorite', {params: params})
  }, 

  //小红书学院
  async getArticleList({ commit }, params) {
    return await this.$axios.$get('api/v1/article/search', {params: params})
  },

  //小红书学院 - 获取文章详情
  async getArticleDetail({ commit }, params) {
    return await this.$axios.$get(`api/v1/article/${params}`)
  }

}

接口调用

asyncData ({isDev, route, store, env, params, query, req, res, redirect, error}) {
        let data = {
            page: query.page,
            per_page: query.per_page,
            title: query.t
        }
        return store.dispatch('getArticleList', data).then(res => {
            return { 
                resData: res.data.list,
                totalCount: res.data.totalCount,
                params: {
                    page: query.page ? Number(query.page) : 1,
                    per_page: query.per_page ? Number(query.per_page) : 10
                }
            };
        })
    },

watchQuery

使用watchQuery属性可以监听参数字符串的更改。 如果定义的字符串发生变化,将调用所有组件方法(asyncData, fetch, validate, layout, ...)。

watchQuery: ['page', 'per_page'],

你可能感兴趣的:(@nuxtjs/axios)