Skip to content

Commit

Permalink
docs(proxy events): fix new syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
chimurai committed Apr 16, 2022
1 parent d6f0d17 commit 79306c6
Show file tree
Hide file tree
Showing 3 changed files with 104 additions and 82 deletions.
14 changes: 9 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -510,7 +510,9 @@ const proxy = createProxyMiddleware({
/**
* Fix bodyParser
**/
onProxyReq: fixRequestBody,
on: {
proxyReq: fixRequestBody,
},
});
```

Expand Down Expand Up @@ -538,10 +540,12 @@ const proxy = createProxyMiddleware({
/**
* Intercept response and replace 'Hello' with 'Goodbye'
**/
onProxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
const response = responseBuffer.toString('utf8'); // convert buffer to string
return response.replace('Hello', 'Goodbye'); // manipulate response and return the result
}),
on: {
proxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
const response = responseBuffer.toString('utf8'); // convert buffer to string
return response.replace('Hello', 'Goodbye'); // manipulate response and return the result
}),
},
});
```

Expand Down
70 changes: 39 additions & 31 deletions recipes/async-response.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,27 @@ const myProxy = createProxyMiddleware({
target: 'http://www.example.com/api',
changeOrigin: true,
selfHandleResponse: true,
onProxyReq: (proxyReq, req, res) => {
// before
proxyReq.setHeader('mpth-1', 'da');
},
onProxyRes: async (proxyRes, req, res) => {
const da = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ wei: 'wei' });
}, 200);
});
on: {
proxyReq: (proxyReq, req, res) => {
// before
proxyReq.setHeader('mpth-1', 'da');
},
}
on: {
proxyRes: async (proxyRes, req, res) => {
const da = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ wei: 'wei' });
}, 200);
});

// add your dynamic header
res.setHeader('mpth-2', da.wei);
// add your dynamic header
res.setHeader('mpth-2', da.wei);

// now pipe the response
proxyRes.pipe(res);
},
// now pipe the response
proxyRes.pipe(res);
},
}
});

app.use('/api', myProxy);
Expand All @@ -48,25 +52,29 @@ const myProxy = createProxyMiddleware({
target: 'http://www.example.com/api',
changeOrigin: true,
selfHandleResponse: true,
onProxyReq: (proxyReq, req, res) => {
// before
// get something async from entry middleware before the proxy kicks in
console.log('proxyReq:', req.locals.da);
on: {
proxyReq: (proxyReq, req, res) => {
// before
// get something async from entry middleware before the proxy kicks in
console.log('proxyReq:', req.locals.da);

proxyReq.setHeader('mpth-1', req.locals.da);
},
onProxyRes: async (proxyRes, req, res) => {
const da = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ wei: 'wei' });
}, 200);
});
proxyReq.setHeader('mpth-1', req.locals.da);
},
}
on: {
proxyRes: async (proxyRes, req, res) => {
const da = await new Promise((resolve, reject) => {
setTimeout(() => {
resolve({ wei: 'wei' });
}, 200);
});

// end:
res.setHeader('mpth-2', da.wei);
// end:
res.setHeader('mpth-2', da.wei);

proxyRes.pipe(res);
},
proxyRes.pipe(res);
},
}
});

app.use('/api', entryMiddleware, myProxy);
Expand Down
102 changes: 56 additions & 46 deletions recipes/response-interceptor.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,14 @@ const proxy = createProxyMiddleware({
/**
* Intercept response and replace 'Hello' with 'Teapot' with 418 http response status code
**/
onProxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
res.statusCode = 418; // set different response status code

const response = responseBuffer.toString('utf8');
return response.replace('Hello', 'Teapot');
}),
on: {
proxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
res.statusCode = 418; // set different response status code

const response = responseBuffer.toString('utf8');
return response.replace('Hello', 'Teapot');
}),
},
});
```

Expand All @@ -39,17 +41,19 @@ const proxy = createProxyMiddleware({

selfHandleResponse: true, // res.end() will be called internally by responseInterceptor()

onProxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
// log original request and proxied request info
const exchange = `[DEBUG] ${req.method} ${req.path} -> ${proxyRes.req.protocol}//${proxyRes.req.host}${proxyRes.req.path} [${proxyRes.statusCode}]`;
console.log(exchange); // [DEBUG] GET / -> http://www.example.com [200]
on: {
proxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
// log original request and proxied request info
const exchange = `[DEBUG] ${req.method} ${req.path} -> ${proxyRes.req.protocol}//${proxyRes.req.host}${proxyRes.req.path} [${proxyRes.statusCode}]`;
console.log(exchange); // [DEBUG] GET / -> http://www.example.com [200]

// log complete response
const response = responseBuffer.toString('utf8');
console.log(response); // log response body
// log complete response
const response = responseBuffer.toString('utf8');
console.log(response); // log response body

return responseBuffer;
}),
return responseBuffer;
}),
},
});
```

Expand All @@ -62,21 +66,23 @@ const proxy = createProxyMiddleware({

selfHandleResponse: true, // res.end() will be called internally by responseInterceptor()

onProxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
// detect json responses
if (proxyRes.headers['content-type'] === 'application/json') {
let data = JSON.parse(responseBuffer.toString('utf8'));
on: {
proxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
// detect json responses
if (proxyRes.headers['content-type'] === 'application/json') {
let data = JSON.parse(responseBuffer.toString('utf8'));

// manipulate JSON data here
data = Object.assign({}, data, { extra: 'foo bar' });
// manipulate JSON data here
data = Object.assign({}, data, { extra: 'foo bar' });

// return manipulated JSON
return JSON.stringify(data);
}
// return manipulated JSON
return JSON.stringify(data);
}

// return other content-types as-is
return responseBuffer;
}),
// return other content-types as-is
return responseBuffer;
}),
},
});
```

Expand Down Expand Up @@ -107,23 +113,25 @@ const proxy = createProxyMiddleware({

selfHandleResponse: true, // res.end() will be called internally by responseInterceptor()

onProxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
const imageTypes = ['image/png', 'image/jpg', 'image/jpeg', 'image/gif'];

// detect image responses
if (imageTypes.includes(proxyRes.headers['content-type'])) {
try {
const image = await Jimp.read(responseBuffer);
image.flip(true, false).sepia().pixelate(5);
return image.getBufferAsync(Jimp.AUTO);
} catch (err) {
console.log('image processing error: ', err);
return responseBuffer;
on: {
proxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
const imageTypes = ['image/png', 'image/jpg', 'image/jpeg', 'image/gif'];

// detect image responses
if (imageTypes.includes(proxyRes.headers['content-type'])) {
try {
const image = await Jimp.read(responseBuffer);
image.flip(true, false).sepia().pixelate(5);
return image.getBufferAsync(Jimp.AUTO);
} catch (err) {
console.log('image processing error: ', err);
return responseBuffer;
}
}
}

return responseBuffer; // return other content-types as-is
}),
return responseBuffer; // return other content-types as-is
}),
},
});

// http://localhost:3000/wikipedia/en/7/7d/Lenna\_%28test_image%29.png
Expand All @@ -146,9 +154,11 @@ const proxy = createProxyMiddleware({
/**
* Intercept response and remove the
**/
onProxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
res.removeHeader('content-security-policy'); // Remove the Content Security Policy header
res.setHeader('HPM-Header', 'Intercepted by HPM'); // Set a new header and value
}),
on: {
proxyRes: responseInterceptor(async (responseBuffer, proxyRes, req, res) => {
res.removeHeader('content-security-policy'); // Remove the Content Security Policy header
res.setHeader('HPM-Header', 'Intercepted by HPM'); // Set a new header and value
}),
},
});
```

0 comments on commit 79306c6

Please sign in to comment.