Axios拦截器使用express req对象

ybzsozfc  于 2023-08-04  发布在  iOS
关注(0)|答案(2)|浏览(106)

我有一个快速路由,我从前端发送一个头,在这个路由中,我使用axios发出GET请求。我用axios创建了一个拦截器,但我希望能够从激活的路由中读取req对象,以便将头添加到axios GET调用中。

// 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({});
});

字符串
有可能做到这一点吗?

0ejtzxu1

0ejtzxu11#

所以我认为这样做的方法是使用中间件来设置头,并传递Axios示例

// apiSetHeader.js middleware
exports.default = (req, res, next) => {
  req.CustomAxios = axios.create({
    headers: { 'HeaderForTheApi': req.headers.apiHeader'}
  })
  next()
}

字符串
然后在你的路线中使用它

// 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({});
});


希望这对你有帮助!

mkh04yzy

mkh04yzy2#

我会这么做
1.创建一个自定义的express中间件,将axios示例作为参数,并添加到axios header或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.然后创建你的axios示例并使用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.现在,您的axios请求或响应拦截器应该可以访问添加的值:

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),
);


更多信息,请参阅express和axios docs

相关问题