如何从 js 文件访问 Nuxt 上下文

时间:2021-03-31 18:04:03

标签: vue.js axios nuxt.js

我在单独的文件中向 API 发出请求,例如:

// ~/api/request.ts

import axios from 'axios'

export const testMethod = async (
  email: string
) => {
  try {
    return await axios.post('/test-route/', { email })
  } catch (error) {
    if (error.code === '401') {
      //
    }
  }
}

我想要:

  1. 要添加错误处理,如果令牌已过期,则重定向到授权页面并清除存储。
  2. 使用授权标头创建 axios 实例,使用来自 Vuex 的令牌

如何从此文件访问 Nuxt 上下文?

1 个答案:

答案 0 :(得分:0)

我可以建议把这个逻辑放到 vue mixin 中。然后就可以和 vue/nuxt 上下文交互了。