【问题标题】:Nuxt JS middleware cant use axiosNuxt JS 中间件不能使用 axios
【发布时间】:2021-07-01 23:15:18
【问题描述】:

我想创建一个中间件来检查令牌是否有效,但是 axios 无法读取。任何人都可以帮助我如何找到解决方案。这是我的代码:

中间件/authentication.js

export default  ({ app, redirect }) => {

    let data = {
      'userid': app.$cookies.get('user_id'),
      'token': app.$cookies.get('auth_token'),
    };

    app.$axios.post(`/tokenVerify`,data)
    .then(res => {
      console.log(res)
    })
 }

pages/index.vue

    export default {
        middleware: "authentication",

nuxt.config.js

  modules: [
    '@nuxtjs/axios',
  ],
   axios: {
    proxy: true,
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Accept' : 'application/json, text/plain, */*',
      'Access-Control-Allow-Methods' : 'GET, PUT, POST, DELETE, OPTIONS',
      'Access-Control-Allow-Credentials' : true,
    }
  },

    proxy: {
        '/tokenVerify':{target:process.env.BASE_URL+'index.php/public/tokenVerify', pathRewrite: {'^/tokenVerify': ''}, changeOrigin: true},
        '/vimeoEmbed':{target:'https://vimeo.com/api/oembed.json', pathRewrite: {'^/vimeoEmbed': ''}, changeOrigin: true},
  },

  


【问题讨论】:

  • 您不应该在您的身份验证中间件中调用redirect 吗?您所做的只是记录结果。
  • 目前,我没有使用重定向。我只想阅读 axios 函数,.. 和 console.log 结果。但在那种情况下,axios 没有读取它,.. 而且它们在 Network/XHR 记录中也没有检测到

标签: javascript vue.js axios nuxt.js nuxtjs


【解决方案1】:

您将$axios 服务注入到中间件上下文参数中。所以你应该可以像这样访问它:

export default  ({ app, redirect, $axios }) => {
    let data = {
      'userid': app.$cookies.get('user_id'),
      'token': app.$cookies.get('auth_token'),
    };

    $axios.post(`/tokenVerify`,data)
    .then(res => {
      console.log(res)
    })
 }

【讨论】:

  • 我试过了,但是还是看不懂axios代码,..顺便说一下,我用的是SSR开发,.
  • 那么不幸的是我不确定发生了什么。我们还在 SSR 模式下使用 Nuxt,以上对我们有用。
【解决方案2】:

就我而言,我正在使用带有 spa 模式的 nuxt。

我已经为 axios [axios.js 在插件文件夹中] 构建了一个 nuxt 插件,并使用该插件注入应用程序,就像这样...

export default function ({ $axios, redirect, app }, inject) {
  // Create a custom axios instance
  const axios = $axios.create({
    headers: {
      common: {
        Accept: "text/plain, */*",
      },
    },
  });

  axios.setBaseURL(process.env.NUXT_ENV_BASE_URL);

  /**
   * Request interceptor
   */
  axios.onRequest((config) => {
    const token = app.store.getters.token || "";

    if (token) {
      if (config.method !== "OPTIONS") {
        config.headers.authorization = `${token}`;
      }
    }

    return config;
  });

  /**
   * Response interceptor
   */
  axios.onResponse((response) => {
    return response.data;
  });

  /**
   * Error interceptor
   */
  axios.onError((error) => {
    if (!error || !error.response || !error.response.status) {
      app.$notify({
        group: "all",
        title: "Network Error",
        text: `Can not connect to the server.`,
        type: "info",
      });

      return;
    }
  });

  // Inject to context as $axios
  inject("axios", axios);
}

我已经在nuxt.config.js 文件中定义了插件位置。像这样..

plugins: [
  "~/plugins/axios"
]

现在,在我的中间件中,我可以像这样访问 axios ...

export default function (context) {
  context.app.$axios
    .get(API_LINK)
    .then((res) => {
      console.log(res);
    })
    .catch((e) => {
      console.log(e);
    });
}

它对我有用。 如果您需要进一步解释,请告诉我。

【讨论】:

    猜你喜欢
    • 2020-06-04
    • 2020-04-02
    • 2020-09-25
    • 2020-11-15
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 2021-12-06
    相关资源
    最近更新 更多