Proxy with express.js Proxy with express.js express express

Proxy with express.js


request has been deprecated as of February 2020, I'll leave the answer below for historical reasons, but please consider moving to an alternative listed in this issue.

Archive

I did something similar but I used request instead:

var request = require('request');app.get('/', function(req,res) {  //modify the url in any way you want  var newurl = 'http://google.com/';  request(newurl).pipe(res);});

I hope this helps, took me a while to realize that I could do this :)


I found a shorter and very straightforward solution which works seamlessly, and with authentication as well, using express-http-proxy:

const url = require('url');const proxy = require('express-http-proxy');// New hostname+path as specified by question:const apiProxy = proxy('other_domain.com:3000/BLABLA', {    proxyReqPathResolver: req => url.parse(req.baseUrl).path});

And then simply:

app.use('/api/*', apiProxy);

Note: as mentioned by @MaxPRafferty, use req.originalUrl in place of baseUrl to preserve the querystring:

    forwardPath: req => url.parse(req.baseUrl).path

Update: As mentioned by Andrew (thank you!), there's a ready-made solution using the same principle:

npm i --save http-proxy-middleware

And then:

const proxy = require('http-proxy-middleware')var apiProxy = proxy('/api', {target: 'http://www.example.org/api'});app.use(apiProxy)

Documentation: http-proxy-middleware on Github

I know I'm late to join this party, but I hope this helps someone.


You want to use http.request to create a similar request to the remote API and return its response.

Something like this:

const http = require('http');// or use import http from 'http';/* your app config here */app.post('/api/BLABLA', (oreq, ores) => {  const options = {    // host to forward to    host: 'www.google.com',    // port to forward to    port: 80,    // path to forward to    path: '/api/BLABLA',    // request method    method: 'POST',    // headers to send    headers: oreq.headers,  };  const creq = http    .request(options, pres => {      // set encoding      pres.setEncoding('utf8');      // set http status code based on proxied response      ores.writeHead(pres.statusCode);      // wait for data      pres.on('data', chunk => {        ores.write(chunk);      });      pres.on('close', () => {        // closed, let's end client request as well        ores.end();      });      pres.on('end', () => {        // finished, let's finish client request as well        ores.end();      });    })    .on('error', e => {      // we got an error      console.log(e.message);      try {        // attempt to set error message and http status        ores.writeHead(500);        ores.write(e.message);      } catch (e) {        // ignore      }      ores.end();    });  creq.end();});

Notice: I haven't really tried the above, so it might contain parse errors hopefully this will give you a hint as to how to get it to work.