Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios interceptor use express req object

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?

like image 597
Raphael Avatar asked Nov 28 '25 23:11

Raphael


2 Answers

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!

like image 90
Balázs Zákány Avatar answered Nov 30 '25 17:11

Balázs Zákány


Here's how I'd do it:

  1. Create a custom express middleware that takes an axios instance as a parameter and adds to the axios headers or config:
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();
  };
}
  1. Then just create your axios instance and use the middleware in express:
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));
  1. Now, your axios request or response interceptor should have access to the value added:
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.

like image 23
WesleyAC Avatar answered Nov 30 '25 15:11

WesleyAC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!