Can I forward an http request from one node.js or python server to another server?

1.4k Views Asked by At

Hello I have this question I have not found an anwser yet. I would like to create something like the image I attach. Final Structure I want to realize

The normal workflow should be something like this:

  1. Client sends a request to server 1;
  2. Server 1 receives the request;
  3. Server 1 sends a 302 (redirect) response to the client;
  4. Then client sends a new http request to server 2;
  5. Server 2 receives the request;
  6. Server 2 sends a 200 (ok) response to the client;

Instead of this I would like to realize something like:

  1. Client sends a request to server 1;
  2. Server 1 receives the request;
  3. Server 1 forward the request to server 2;
  4. Server 2 receives the request;
  5. Server 2 sends a direct response to the client;

So I do not want to send a redirect response from server 1 to client and then a new request from client to server 2!

It could be possible to realize something like this with node.js or, at least, with python?. I want this kind of architecture to speed up my service because server-server connection is far much faster then client-server connection.

2

There are 2 best solutions below

2
On

If you need to do some logic before server1 perform the request to server2 (for example selecting the endpoint in server 2 based on some condition on request) then you can use request function from the Node.js standard library http module (see docs at https://nodejs.org/dist/latest-v4.x/docs/api/http.html#http_http_request_options_callback). But if you don't need to perform any logic then is better to go with https://www.npmjs.com/package/http-proxy because you avoid a lot of boilerplate code.

2
On

You need to use a proxy.

Something like https://www.npmjs.com/package/http-proxy

or you can use nginx or similar in front of a node.js server to be the proxy.

The only thing is the requests have to go back through the proxy, because thats how tcp connections work