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

In you case res.redirect might help.

app.get('/track', function(req, res) {
   // process the request

   // then redirect
   res.redirect('/final-endpoint');
});

Then catch the redirected request in final endpont.

app.get('/final-endpoint', function(req, res) {
       // proceess redirected request here.
});

See the Express docs


If your second endpoint is on a different server, (e.g. PHP) then you're going to need to either redirect the client (as in sohel's answer), or spoof a request from Node to the PHP server and then send the response back to the client. This latter option is definitely non-trivial so I would question whether it's crucial not to use a client redirect.

If you're talking about two express endpoints, then I think the simplest answer might be not to actually forward at all, but just use the endpoint callback directly instead:

app.get('/track', trackCallback);
app.get('/otherendpoint', otherendpointCallback);

function otherendpointCallback(req, res) {
  // do your thing
}

function trackCallback(req, res) {

  otherendpointCallback(req, res);

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

Depending on exactly what you want to do at the other end point, you might need to spoof some of req's fields (e.g. req.url)


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


There are a couple of useful libraries that one could use:

http-proxy-middleware:

const proxy = require('http-proxy-middleware')
var apiProxy = proxy('/track', {target: 'http://end-point'});
app.use(apiProxy)

axios-express-proxy

import express from 'express';
import { Proxy } from 'axios-express-proxy';
const app = express();
const port = 3000;

app.get('/track', (req, res) => Proxy('http://end-point', req, res));

Tags:

Node.Js