I have a project based on a NuxtJS front end, connecting to a .NET legacy application via API layer. It's likely that the legacy backend will also be switched out in the not too distant future, so we've used the server-middleware part of Nuxt to create an abstraction between our UI and the back end. No matter what technology we use in the future to serve the back end, we're going to have similar business needs and that middleware should allow us to bridge between the two systems without having to completely re-write our UI.
Especially during debug, it's very useful to be able to see the traffic going through that server middleware - enter Axios Interceptors!
This code does a few things:
Firstly, this is an axios instance that can be re-used in all of my API components, so any logging that happens here can be extended, removed or disabled for all APIs with minimal code changes - and all the logging will have exactly what I expect each time.
In this form, only error responses will be logged to the server - but the logs will contain everything about the request and the response from the server - VERY useful when you're not only development the UI, but also working on the API layer at the same time.
For simpler checking of the data being passed through, the request interceptors can also log to confirm the sequence of operations and that the correct API calls are being made - just be aware this can create a LOT of logging!
One caution - in the event of an error - this will log EVERYTHING to the console and (in production) to the server logs, including any secure headers which may include secure subscription keys or tokens. Normal rules of engagement apply - don't leave the logging turned on and/or extend this method to redact anything sensitive!
import { environment } from '../../../config'
const axios = require('axios')
const instance = axios.default.create({
baseURL:`${environment.apiprotocol}${environment.cmsServer.url}/`,
timeout: 40000
})
instance.interceptors.request.use(
function (request) {
// console.log('Request:', request.method, (instance.defaults.baseURL + request.url))
return request
},
function (error) {
// console.log('Request error:', error.response.status, error.response.message)
return Promise.reject(error)
})
instance.interceptors.response.use(
function (response) {
// console.log('Response:', response.status, response.statusText)
return response
},
function (error) {
console.log('Response error:', error)
if (error.response) {
console.log('Error', error.response.status, error.response.data)
}
console.log('Config', error.config)
return Promise.reject(error)
})
module.exports = instance