node.js

How to forward a request to other endpoint in node.js


In my scenario I need forward get request to another end point. In my machine there are two servers php and node.js server. Node.js is like a "man in the middle", PHP server must work in the same way.

Node.js server code

var express = require('express');
var fs = require('fs');
var path = require('path');
var http = require('http');
var https = require('https');
var app = express();

var HTTP_PORT = 3000;

// Create an HTTP service
http.createServer(app).listen(HTTP_PORT,function() {
  console.log('Listening HTTP on port ' + HTTP_PORT);
});


//endpoint for tracking
app.get('/track', function(req, res) {

  sendRequestToOtherEndPoint(req);

  processRequest(req);
  res.setHeader('Content-Type', 'application/json');
  res.send('Req OK');
});

function processRequest(req){
    console.log("request processed");
}

function sendRequestToOtherEndPoint(req){
    //magic here :)
}

When this server receive a get request in port 3000, it process request information and it must forward the same requesto to another end point.

For example:

  1. Get localhost:3000/track?param1=1&param2=2
  2. Server process get request
  3. Server forward get request to localhost/final-endpoint?param1=1&param2=2

Solution

  • Depending on what you're trying to do, you can create a new request to the end-point:

    //endpoint for tracking
    app.get('/track', function(req, res) {
    
      req.get({url: 'http://end-point', headers: req.headers});
    
      processRequest(req);
      res.setHeader('Content-Type', 'application/json');
      res.send('Req OK');
    });
    

    More info: https://github.com/request/request