Currently utilizing the Nuxt-axios module alongside a proxy.
Implemented common error handling code in
Plugins/axios.js
export default function({ $axios, __isRetryRequest, store, app, redirect , payload , next}) {
$axios.onRequest(config => {
if (app.$cookies.get('at') && app.$cookies.get('rt') && config.url != '/post_login/') {
config.headers.common['Authorization'] = `Bearer ${app.$cookies.get('at')}`;
}
});
$axios.onResponseError(err => {
const code = parseInt(err.response && err.response.status)
let originalRequest = err.config;
if (code === 401) {
originalRequest.__isRetryRequest = true;
store
.dispatch('LOGIN', { grant_type: 'refresh_token', refresh_token: app.$cookies.get('rt')})
.then(res => {
originalRequest.headers['Authorization'] = 'Bearer ' + app.$cookies.get('at');
return app.$axios(originalRequest);
})
.catch(error => {
console.log(error);
});
}
// Error handling for status code 422
if (code == 422) {
throw err.response;
}
});
}
In the index file within the pages folder
Pages/index.vue
<template>
<section>Component data</section>
</template>
<script type="text/javascript">
export default {
async asyncData({ route, store }) {
await store.dispatch('GET_BANNERS');
}
}
</script>
All API calls are handled in a stores/actions.js file.
When refreshing the page, the first API request from 'asyncData' will be made. If this initial request ('GET_BANNERS') encounters a 401 unauthorized error, the following error is displayed:
Error: Request failed with status code 401
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
To address this issue, there are additional questions:
Additional Queries:
1) When defining common error handling code in axios, how can I update store data again after receiving a 401 response on the original request?
2) Can someone provide guidance on best practices for setting authorization headers and handling errors like 400, 401, and 422?