最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Nuxt JS middleware cant use axios - Stack Overflow

matteradmin6PV0评论

I want to create a middleware to check if token is valid, but the axios cant read. Anyone can help me how to find solution. this si my code:

middleware/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:'.json', pathRewrite: {'^/vimeoEmbed': ''}, changeOrigin: true},
  },

  


I want to create a middleware to check if token is valid, but the axios cant read. Anyone can help me how to find solution. this si my code:

middleware/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./api/oembed.json', pathRewrite: {'^/vimeoEmbed': ''}, changeOrigin: true},
  },

  


Share Improve this question asked Apr 6, 2021 at 7:04 AbingPjAbingPj 6599 silver badges21 bronze badges 2
  • Aren't you supposed to call redirect in your auth middleware? All you're doing is logging the result. – user5734311 Commented Apr 6, 2021 at 7:08
  • Currently, I did not use the redirect. I Just want to read the axios function,.. and console.log the result. but on that case axios not reading it,.. and also their is no detection in Network/XHR records – AbingPj Commented Apr 6, 2021 at 7:21
Add a ment  | 

3 Answers 3

Reset to default 2

You get the $axios service injected into the middleware context parameter. So you should be able to access it like this:

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)
    })
 }

In my case, I'm using nuxt with spa mode.

I have build a nuxt plugin for axios [axios.js in plugin folder] and using that injecting to the application, like this ...

export default function ({ $axios, redirect, app }, inject) {
  // Create a custom axios instance
  const axios = $axios.create({
    headers: {
      mon: {
        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);
}

I have define the plugin location on nuxt.config.js file. Like this ..

plugins: [
  "~/plugins/axios"
]

now, in my middleware, I can access axios like this ...

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

It is working for me. If you need further explanation let me know.

$axios is available in context in the route middleware. But if you are not able to make a request with $axios then try making the request something like this:

export default function ({$axios, req}) {
  $axios
  .get(`http://${req.headers.host}/${API_LINK}`)
    .then((res) => {
      console.log(res);
    })
    .catch((e) => {
      console.log(e);
    });
}

Adding the host name worked for me!!!

Post a comment

comment list (0)

  1. No comments so far