I have an express route in which I send a header from the front end, in this route I'm making a GET request using axios. I created an interceptor with axios, but I would like to be able to read the req object from the activated route in order to add the header to the axios GET call.
// Example Interceptor
axios.interceptors.request.use(
config => {
// How to get req.headers from the route here?
return config;
},
error => {
return Promise.reject(error);
}
);
// Exemple GET route
router.get('/get', async (req, res, next) => {
try {
const { data } = await axios.get('https://kjhf.fsadjhfewq.....');
} catch (error) {
console.log(error)
}
res.status(200).json({});
});
Is it possible to do this?
So I think the way to do this is to use a middleware to set the headers, and pass on the axios instance
// apiSetHeader.js middleware
exports.default = (req, res, next) => {
req.CustomAxios = axios.create({
headers: { 'HeaderForTheApi': req.headers.apiHeader'}
})
next()
}
And then use that in your route
// Exemple GET route
router.get('/get', apiSetHeaderMiddleware, async (req, res, next) => {
try {
const { data } = await req.CustomAxios.get('https://kjhf.fsadjhfewq.....');
} catch (error) {
console.log(error)
}
res.status(200).json({});
});
Hope this helps!
Here's how I'd do it:
function customMiddleware(axiosInstance) {
return (req, res, next) => {
//add to axios config
axiosInstance.defaults['token'] = '<whatever you want>';
//or add to axios header
//axiosInstance.defaults.headers.common['token'] = <whatever you want>;
next();
};
}
const express = require('express');
const axios = require('axios');
const axiosInstance = axios.create({
baseURL: 'http://www.example.com',
//...whatever else you need
});
const app = express();
app.use(customMiddleware(axiosInstance));
axiosInstance.interceptors.request.use(
(axiosConfig) => console.log(axiosConfig.token),
//or axiosConfig.headers.token if added as a header
(error) => console.log(error),
);
axiosInstance.interceptors.response.use(
(axiosResponse) => console.log(axiosResponse.config.token),
//or axiosResponse.config.headers.token if added as a header
(error) => console.log(error),
);
Consult the express and axios docs for more information.
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