繁体   English   中英

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

[英]Node Http Proxy - basic reverse proxy doesn't work (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://www.google.co.uk/images/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头。

Vhosted站点依赖此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
}));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM