nodejs proxy not responding
I have a node.js app that serve static files (html, js, css). Among the static files, some ajax request are done (with /TEST in the request). I need those request to be proxied to another server running on localhost:213445. The static pages are correctly displayed but when it comes to proxied request it hangs forever...
My code is:
var express = require("express");
var httpProxy = require('http-proxy');
var fs = require('fs');
// Create https server
var app = express.createServer({
key: fs.readFileSync('privatekey.pem'),
cert: fs.readFileSync('certificate.pem')
});
// Handle static files
app.use(express.static(__dirname + '/public'));
// Proxy request
app.all('/TEST/*',function(req, res){
// Remove '/TEST' part from query string
req.url = '/' + req.url.split('/').slice(2).join('/');
// Create proxy
var proxy = new httpProxy.HttpProxy();
proxy.proxyRequest(req, res, {
host: 'localhost',
port: 21345,
enableXForwarded: false,
buffer: proxy.bu开发者_运维技巧ffer(req)
});
});
// Run application
app.listen(10443);
I have the same issue. If you comment out the
// Handle static files
app.use(express.static(__dirname + '/public'));
you will see that the the proxy works.
Not sure how to fix it if express.static is used
Marak Squires responded to the bug report!
This is an express problem. The Connect / Express middlewares are doing non-standard things to your response object, breaks streaming. Try using the raw
request
module instead ofhttp-proxy
. If you need proper middleware stack, check out https://github.com/flatiron/union
As described on the http-proxy issue 180 the trouble is related to the non-standard things done by connect mentioned above:
Use npm to install connect-restreamer and make this the final item in your app.configuration of express:
app.use(require('connect-restreamer')());
Then do something like:
var httpProxy = require('http-proxy');
var routingProxy = new httpProxy.RoutingProxy();
app.get('/proxy/', function (req, res) {
routingProxy.proxyRequest(req, res, {
target: {
host : host,
port : port
}
});
})
This will pass the whole URL, including "/proxy/" to the target host. You can rewrite/modify the headers of the req before they go into the proxyRequest()
if you, e.g. want to mimic the request coming from a specific CNAME virtual host or different URL string.
精彩评论