|
| 1 | +# Async proxied response |
| 2 | + |
| 3 | +Sometimes we need the ability to modify the response headers of the response of the proxied backend before sending it. For achieving it just make sure you have selfHandleResponse to true and add a pipe in the proxyRes: |
| 4 | + |
| 5 | +```javascript |
| 6 | +const myProxy = createProxyMiddleware({ |
| 7 | + target: 'http://www.example.com', |
| 8 | + changeOrigin: true, |
| 9 | + selfHandleResponse: true, |
| 10 | + onProxyReq: (proxyReq, req, res) => { |
| 11 | + // before |
| 12 | + proxyReq.setHeader('mpth-1', 'da'); |
| 13 | + }, |
| 14 | + onProxyRes: async (proxyRes, req, res) => { |
| 15 | + const da = await new Promise((resolve, reject) => { |
| 16 | + setTimeout(() => { |
| 17 | + resolve({ wei: 'wei' }); |
| 18 | + }, 200); |
| 19 | + }); |
| 20 | + |
| 21 | + // add your dynamic header |
| 22 | + res.setHeader('mpth-2', da.wei); |
| 23 | + |
| 24 | + // now pipe the response |
| 25 | + proxyRes.pipe(res); |
| 26 | + }, |
| 27 | +}); |
| 28 | + |
| 29 | +app.use('/api', myProxy); |
| 30 | +``` |
| 31 | + |
| 32 | +There are also cases where you need to modify the request header async, we can achieve this by applying middleware in front of the proxy. Like: |
| 33 | + |
| 34 | +```javascript |
| 35 | +const entryMiddleware = async (req, res, next) => { |
| 36 | + const foo = await new Promise((resolve, reject) => { |
| 37 | + setTimeout(() => { |
| 38 | + resolve({ da: 'da' }); |
| 39 | + }, 200); |
| 40 | + }); |
| 41 | + req.locals = { |
| 42 | + da: foo.da, |
| 43 | + }; |
| 44 | + next(); |
| 45 | +}; |
| 46 | + |
| 47 | +const myProxy = createProxyMiddleware({ |
| 48 | + target: 'http://www.example.com', |
| 49 | + changeOrigin: true, |
| 50 | + selfHandleResponse: true, |
| 51 | + onProxyReq: (proxyReq, req, res) => { |
| 52 | + // before |
| 53 | + // get something async from entry middlware before the proxy kicks in |
| 54 | + console.log('proxyReq:', req.locals.da); |
| 55 | + |
| 56 | + proxyReq.setHeader('mpth-1', req.locals.da); |
| 57 | + }, |
| 58 | + onProxyRes: async (proxyRes, req, res) => { |
| 59 | + const da = await new Promise((resolve, reject) => { |
| 60 | + setTimeout(() => { |
| 61 | + resolve({ wei: 'wei' }); |
| 62 | + }, 200); |
| 63 | + }); |
| 64 | + |
| 65 | + // end: |
| 66 | + res.setHeader('mpth-2', da.wei); |
| 67 | + |
| 68 | + proxyRes.pipe(res); |
| 69 | + }, |
| 70 | +}); |
| 71 | + |
| 72 | +app.use('/api', entryMiddleware, myProxy); |
| 73 | +``` |
| 74 | + |
| 75 | +_working sample available at: [codesandbox.io/s/holy-resonance-yz552](https://codesandbox.io/s/holy-resonance-yz552?file=/src/index.js) Server Control Panel: restart server, see logging_ |
0 commit comments