moll / node-mitm

Intercept and mock outgoing Node.js network TCP connections and HTTP requests for testing. Intercepts and gives you a Net.Socket, Http.IncomingMessage and Http.ServerResponse to test and respond with. Super useful when testing code that hits remote servers.
Other
640 stars 48 forks source link

Intercept http call and change the path in URL #64

Closed amar02041988 closed 2 months ago

amar02041988 commented 4 years ago

First of all, thanks for this wonderful utility. I wanted to intercept the http call and update host,port and path(uri) in the url and then let the request flow to this other http service. I am able to change the host and port but not able to change the path. Below is the code:

Wanted to re-write the url from http://api-gateway:8080/service/compression to http://localhost:3000/local/service/compression. Not able to change the path from service/compression to local/service/compression

mitm.on('connect', (socket, opts) => { opts.host = "localhost"; opts.port = 3000; opts.pathname = "local/" + opts.pathname; // Do thing is not updating the uri path socket.bypass(); });

Please let me know what should be done to change the path as well

moll commented 4 years ago

Hey,

You're welcome.

Changing the path in this situation is going to be a tad more difficult as then you're not merely bypassing the intercept, but actually reading its body, changing it to your liking and retransmitting it in a new connection. Perhaps this thread could help and direct you to a working solution: https://github.com/moll/node-mitm/issues/51.

Depending on how much control you have over the code you're trying to intercept, you could also just overwrite require("http").request yourself and skip using Mitm.js entirely. That would permit you to change the outgoing request at a higher level than Mitm.js would permit.

moll commented 2 months ago

I'll close the issue for now as there's nothing particularly actionable, but we can continue chatting on how to implement proxying.