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?
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}`;
});
}
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,
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With