Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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
like image 898
mjimcua Avatar asked Aug 21 '15 13:08

mjimcua


People also ask

How do I forward a node js request?

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.


1 Answers

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

like image 139
kmandov Avatar answered Oct 08 '22 14:10

kmandov