Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set global $axios header in NuxtJS

I've been trying to get this to work for two days now. I'm a brand new user to Nuxt (although I've used Vue for a few years now), so I'm just trying to wrap my brain around how this all works.

In my Nuxt project I have the Axios module installed:

nuxt.config.js

export default {
  plugins: [
    ...
    '~/plugins/axios',
  ],
  axios: {
    baseURL: 'https://my-url.com/wp-json/wp-v2',
    https: true,
  },
}

plugins/axios.js

export default ({ $axios, env }) => {
  $axios.onRequest(config => {
    $axios.setToken(env.WP_API_KEY, 'Bearer');
  });
}

And in my page, I'm trying to use the asyncData function to pull data from my WordPress API, as such:

export default {
  async asyncData(context) {
    const data = await context.$axios.$get('/media');
    console.log(data);
    return { data };
  }
}

I keep receiving a 401 Not Authorized error however, essentially stating that my Authorization: Bearer <token> isn't being passed through. Using Postman however, I can verify that this endpoint does indeed work and returns all of the JSON I need, so the problem must lie in the way I have the axios global header set up.

It's been tough finding any real example on how to set a global header using the Nuxt/Axios module. I see in the docs how to use setToken, however it doesn't exactly show where to place that.

What do I have set up wrong, and how do I fix it?

like image 736
J. Jackson Avatar asked May 25 '20 17:05

J. Jackson


2 Answers

Pretty typical that I get it working 15 minutes after I post a question.

Setting the header like this instead seems to work. I'm not sure why the setToken method didn't want to work.

export default ({ $axios, env }) => {
  $axios.onRequest(config => {
    config.headers.common['Authorization'] = `Bearer ${env.WP_API_KEY}`;
  });
}
like image 62
J. Jackson Avatar answered Oct 21 '22 08:10

J. Jackson


If you are using Nuxt auth module, Here is how I have achived.

// nuxt.config.js
modules: [
 '@nuxtjs/auth',
 '@nuxtjs/axios',
],
auth: {
strategies: {
  local: {
    endpoints: {
      login: { url: '/auth/login', method: 'post', propertyName: 'accessToken' },
      logout: false,
      user: { url: '/auth/me', method: 'get', propertyName: false }
    },
  }
},
redirect: {
  login: '/auth/signin',
  logout: '/auth/signin',
  callback: false,
  home: false,
},
cookie: false,
token: {
  prefix: 'token',
},
  plugins: ['~/plugins/auth.js'],
},



// plugins/axios.js
export default function ({ $axios, $auth, redirect, store }) {
$axios.onRequest((config) => {
    config.headers = {
    'Content-Type': 'application/json',
    'Accept': 'application/json',
    'Authorization': store.state.auth.tokenlocal, // refers to nuxt.config.js->auth.token
    }
})

    $axios.onError((error) => {
        if (error.response.status === 500) {
            redirect('/error')
        }
    })
}



// store/index.js
export const getters = {
    authenticated(state) {
        return state.loggedIn;
    },
    user(state) {
        return state.user;
    }
};

export const state = () => ({
    busy: false,
    loggedIn: false,
    strategy: "local",
    user: false,
});
like image 1
Manjunath Reddy Avatar answered Oct 21 '22 08:10

Manjunath Reddy