Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No response using express proxy route

I've written a small proxy with nodejs, express and htt-proxy. It works well for serving local files but fails when it comes to proxy to external api:

var express = require('express'),     app = express.createServer(),     httpProxy = require('http-proxy');   app.use(express.bodyParser()); app.listen(process.env.PORT || 1235);  var proxy = new httpProxy.RoutingProxy();  app.get('/', function(req, res) {     res.sendfile(__dirname + '/index.html'); }); app.get('/js/*', function(req, res) {     res.sendfile(__dirname + req.url); }); app.get('/css/*', function(req, res) {     res.sendfile(__dirname + req.url); });  app.all('/*', function(req, res) {     req.url = 'v1/public/yql?q=show%20tables&format=json&callback=';     proxy.proxyRequest(req, res, {         host: 'query.yahooapis.com', //yahoo is just an example to verify its not the apis fault         port: 8080     });  }); 

The problem is that there is no response from the yahoo api, maybe there is an response but i dont came up in the browser.

like image 495
Andreas Köberle Avatar asked Sep 26 '11 18:09

Andreas Köberle


People also ask

Is express a reverse proxy?

express-http-proxy is the HTTP reverse proxy library.

What is trust proxy in Express?

Indicates the app is behind a front-facing proxy, and to use the X-Forwarded-* headers to determine the connection and the IP address of the client. NOTE: X-Forwarded-* headers are easily spoofed and the detected IP addresses are unreliable.

What is the use of HTTP-proxy-middleware?

The http-proxy-middleware module does not return a promise, instead it returns an express middleware. You can use a custom filter to decide whether or not to proxy the request. You need to add the pathRewrite options in order to rewrite the url according to the current hostname.


1 Answers

Even simpler with pipe and request-Package

var request = require('request');  app.use('/api', function(req, res) {   var url = apiUrl + req.url;   req.pipe(request(url)).pipe(res); }); 

It pipes the whole request to the API and pipes the response back to the requestor. This also handles POST/PUT/DELETE and all other requests \o/

If you also care about query string you should pipe it as well

req.pipe(request({ qs:req.query, uri: url })).pipe(res); 
like image 184
Stephan Hoyer Avatar answered Sep 28 '22 09:09

Stephan Hoyer