In nodejs trying to get an HTTP proxy to forward requests going through query string parameters

How to proxy requests with query string parameters in nodejs, I am currently using express and http-proxy?

I have a nodejs app using express and a http-proxy module to proxy HTTP GET requests from specific paths at my end for a third party API running on the same server but with a different port (and hence the same problem origin, requiring a proxy). This works fine as long as I don't want to call the REST function in the front-end API with query string parameters, ie "? Name = value". Then I get 404.

var express = require('express');
var app = express();
var proxy = require('http-proxy');
var apiProxy = proxy.createProxyServer();

app.use("/backend", function(req,res){
    apiProxy.web(req,res, {target: 'http://'+ myip + ':' + backendPort + '/RestApi?' + name + '=' + value});
});

      

Chrome console shows:

"GET http://localhost:8080/backend 404 (Not Found)"

      

Notes. I use other things in the expression later, but not before the proximal strings, and I move from more specific to more general when routing the route. The backend can be accessed directly in the browser using the same protocol: // url: port / path? Name = value no problem.

+3


source to share


2 answers


I got this working by changing req.url

to contain the querystring parameters and pass the hostname to the parameter only apiProxy.web

target

:



app.use('/*', function(req, res) {
    var proxiedUrl = req.baseUrl;
    var url = require('url');
    var url_parts = url.parse(req.url, true);
      if (url_parts.search !== null) {
        proxiedUrl += url_parts.search;
    }

    req.url = proxiedUrl;

    apiProxy.web(req, res, {
      target: app.host
    });
});

      

+5


source


2017 Update

The proxy server query options and query string pass v4 property Express originalUrl

:



app.use('/api', function(req, res) {

  req.url = req.originalUrl    //<-- Just this!

  apiProxy.web(req, res, {
    target: {
      host: 'localhost',
      port: 8080
    }
  })

      

+2


source







All Articles