Replies: 38 comments
-
I don't have the answer unfortunately. You are not the first one the ask this question. (#91 (comment)) Happy to add this one to the http-proxy-middleware recipes. Maybe this example might help you: Can you post this question on StackOverflow (with backlink)? Hopefully your question will get an answer there. Thanks! Update 2021-04-18:
|
Beta Was this translation helpful? Give feedback.
-
I tried to use https://github.com/langjt/node-http-proxy-json And it seems to solve my problem. Note that the library is still fairly new, but it's definitely take out some pain points from many people that has the same issues. Let me just quote my code here for people who is interested, Hope it helps :) @chimurai You can even add that to your recipe if you think it is good enough. import express from 'express';
import proxy from 'http-proxy-middleware';
import config from 'config';
import modifyResponse from 'node-http-proxy-json';
const router = new express.Router();
const myProxy = proxy(config.get('some.json.api.Url'), {
changeOrigin: true,
logLevel: 'debug',
pathRewrite: (path, req) => path.replace('/api', '/_ajax'),
onProxyRes(proxyRes, req, res) {
delete proxyRes.headers['content-length'];
modifyResponse(res, proxyRes.headers['content-encoding'], function (body) {
if (body) {
// modify some information
body.version = 2;
body.props = {
"nestedProps": true
};
}
return body;
});
},
});
router.use('/api/example', myProxy);
export default router;
|
Beta Was this translation helpful? Give feedback.
-
@iroy2000 Thanks for your approach. But I'd like to add custom header from body's property. |
Beta Was this translation helpful? Give feedback.
-
here is my answer, onProxyRes :function(proxyRes, req, res){
var _write = res.write;
var output;
var body = "";
proxyRes.on('data', function(data) {
data = data.toString('utf-8');
body += data;
});
res.write = function (data) {
try{
eval("output="+body)
output = mock.mock(output)
_write.call(res,JSON.stringify(output));
} catch (err) {}
}
} add onProxyRes option on the http-proxy-middleware |
Beta Was this translation helpful? Give feedback.
-
@cokeknight thank you, can you help me more? How do you change header in this approach?
|
Beta Was this translation helpful? Give feedback.
-
Not working for async case, I need return some async data, but it just return nothing. |
Beta Was this translation helpful? Give feedback.
-
@enl31 You can set content-length by this way:
|
Beta Was this translation helpful? Give feedback.
-
This was my final solution (inspired by @kokarn 's solution over at http-party/node-http-proxy#796 I'm using this in a webpack dev server setup by create-react-app, hence the comment further down.
|
Beta Was this translation helpful? Give feedback.
-
If Here is my code
|
Beta Was this translation helpful? Give feedback.
-
I'm currently using @cokeknight 's solution (#97 (comment)), and I'm finding my JSON responses are being truncated after 8192 characters. Is anyone else finding this? N.B. It could be (probably is) because I'm not using the following code snippet... can someone explain what the intention is, and why you wouldn't just do eval("output="+body)
output = mock.mock(output)
_write.call(res, JSON.stringify(output)); (e.g. assign |
Beta Was this translation helpful? Give feedback.
-
Allright, I also used : https://github.com/langjt/node-http-proxy-json and it solved my problem. I recommend it over the manual re-writing of res.write methods - it the same thing as the solutions above, but it's captured in a library. 😅 |
Beta Was this translation helpful? Give feedback.
-
Perhaps the core problem is that response proxy gets from original source is not passed through existing express middleware chain? |
Beta Was this translation helpful? Give feedback.
-
I've been trying to set a cookie which is extracted from the response body but headers are already sent after the response is read. This is one of the ways I tried with {
onProxyRes: (proxyRes, req, res) => {
modifyResponse(res, proxyRes, body => {
res.cookies.set('foo', 'bar')
})
}
} |
Beta Was this translation helpful? Give feedback.
-
@youngzhaosignifyd @westmark
to
|
Beta Was this translation helpful? Give feedback.
-
I needed to
|
Beta Was this translation helpful? Give feedback.
-
Can anyone tell me what type proxyRes is? Documentation features an example or two but I'm desperately looking for an overview/api reference of how it actually works.. |
Beta Was this translation helpful? Give feedback.
-
Just had a minor epiphany and double checked.. |
Beta Was this translation helpful? Give feedback.
-
My solution:
|
Beta Was this translation helpful? Give feedback.
-
@mrt123 's response got us 90% there. But if you need to onProxyRes: (proxyRes, req, res) => {
let originalBody = Buffer.from([]);
proxyRes.on('data', data => {
originalBody = Buffer.concat([originalBody, data]);
});
proxyRes.on('end', () => {
const bodyString = zlib.gunzipSync(originalBody).toString('utf8');
const newBody = doSomeReplacementStuff(bodyString);
res.set({
'content-type': 'text/html; charset=utf-8',
'content-encoding': 'gzip'
});
res.write(zlib.gzipSync(newBody));
res.end();
});
},
selfHandleResponse: true, |
Beta Was this translation helpful? Give feedback.
-
I'm looking to do something similar, but transforming the encoding from latin1 to utf-8. I also need to preserve the original headers, but I'm getting unformatted data. |
Beta Was this translation helpful? Give feedback.
-
I think this is the correct way to do it according to the official documentation modify-response app.use('/api', proxy({
target: 'http://www.example.org',
changeOrigin: true,
selfHandleResponse: true, // so that the onProxyRes takes care of sending the response
onProxyRes: function(proxyRes, req, res) {
var body = new Buffer('');
proxyRes.on('data', function(data) {
body = Buffer.concat([body, data]);
});
proxyRes.on('end', function() {
body = body.toString();
console.log("res from proxied server:", body);
res.end("my response to cli");
});
}
})); |
Beta Was this translation helpful? Give feedback.
-
Not sure why, but when I use @sachinmour's code the "res from proxied server:" has encoding errors, and I mostly see diamonds with question marks inside. Furthermore, when I try to load a page, it gets downloaded, and viewing the file I can see the same encoding errors that I see in terminal or chrome console :( |
Beta Was this translation helpful? Give feedback.
-
Lo-and-behold, the previous example from @eschaefer does not have these encoding errors. I guess I needed gzip...! |
Beta Was this translation helpful? Give feedback.
-
Sorry for adding to an old thread but this may save someone hours and potentially days in searching for a solution to removing headers from an http-proxy response. The way of using selfHandleResponse seems to be a little bit of a blunt instrument for me and it didn't take into consideration streaming and forces the nodejs to buffer the full response before sending and for large files this could be a problem. I found by looking at the library that it would be possible to remove headers for example by looking for the proxyResp events without specifying the selfHandleResponse option, the important thing to note was to ensure that the headers are in the correct order as browsers can be very picky about the ordering of the headers. It is indeed possible to simply to iterate and copy the headers across by object name however this will loose the header order and browsers will start to half load pages or just fail for some content types. Here's a simplified version of proxyRes event listener with the logic i have used - this will allow the proxy to stream as it should and remove headers for example if you don't want to disclose the apache or tomcat version or whatever header you wish to hide. I'm not sure to the extent that it will handle any complex domain rewrites etc that you might have setup and you should test and handle them but it's worth it to keep streaming imho.
Hope it helps someone. Cheers |
Beta Was this translation helpful? Give feedback.
-
how do i modify response with condition? |
Beta Was this translation helpful? Give feedback.
-
I needed to just modify html content, none of the examples above worked for me properly. selfHandleResponse: true,
onProxyRes (proxyRes, req, res) {
const bodyChunks = [];
proxyRes.on('data', (chunk) => {
bodyChunks.push(chunk);
});
proxyRes.on('end', () => {
const body = Buffer.concat(bodyChunks);
// forwarding source status
res.status(proxyRes.statusCode);
// forwarding source headers
Object.keys(proxyRes.headers).forEach((key) => {
res.append(key, proxyRes.headers[key]);
});
// modifying html content
if (proxyRes.headers['content-type'] && proxyRes.headers['content-type'].includes('text/html')) {
let html = body.toString();
// do whatever you want
html = html.replace('foo', 'bar');
res.send(new Buffer.from(html));
} else {
res.send(body);
}
res.end();
});
}, |
Beta Was this translation helpful? Give feedback.
-
This instructs the server to use a different type of compression - you were just lucky, since the server you were trying only supported What you want is Even then, some servers may compress regardless, and you will need @eschaefer's solution to decompress. (source) It would be nice if this package provided a solution to this common problem - compression handled and all. |
Beta Was this translation helpful? Give feedback.
-
Dude you saved my job |
Beta Was this translation helpful? Give feedback.
-
I have tried all solutions above but I keep getting the original response from the server.... In other words res.write(.. or res.end(... doesn't do anything for me...
|
Beta Was this translation helpful? Give feedback.
-
Hi everyone, Created a generic Beta version and details can be found in #515 . Happy to hear your feedback. Feedback will be closed on 2021-04-18. Final version will be published shortly after that. 2021-04-18 update: |
Beta Was this translation helpful? Give feedback.
-
Hi, I'm using Express 4,
In normal way, I can do the following
But how do I execute custom logic if I'm using proxy, let's say I want to manipulate some of the data before response to the user? Is there a good pattern to do that with this middleware ?
app.use('/api', proxy({target: 'http://www.example.org', changeOrigin: true}));
Beta Was this translation helpful? Give feedback.
All reactions