简体   繁体   中英

http-proxy-middleware adding custom header

I'm using http-proxy-middleware to setup request proxy from auth service to secured API.

Here I need to add custom header with authenticated user auth ID for every incoming request to the authentication layer. But with following implementation header not adding to the request. Here I've used on.proxyReq ,

app.use('/info', auth, createProxyMiddleware({
    target: process.env.BASE_API_URL,
    changeOrigin: false,
    on: {
        proxyReq: (proxyReq, req, res) => {
            console.log(`On Proxy Request ${proxyReq}`);
            proxyReq.setHeader('x-auth-user', 'b05ff410-fbba-11ec-bfce-ddefb9f79237');
        },
        proxyRes: (proxyRes, req, res) => {
            console.log(`On Proxy Response ${proxyRes}`);
        },
        error: (err, req, res) => {
            console.log(`On Error Request ${err}`);
        },
    },
}));

This issue has resolved with following,


app.use('/info', auth, createProxyMiddleware({
    target: process.env.BASE_API_URL,
    changeOrigin: false,
    onError: (err, req, res, target) => {
        res.writeHead(500, {
            'Content-Type': 'application/json',
        });
        res.end({ message: 'Something went wrong on proxy request. Please retry.' });
    },
    onProxyReq: (proxyReq, req, res) => {
        proxyReq.setHeader('x_auth_user', req.user.email);
    }
}));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM