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

Node Http Proxy - basic reverse proxy doesn't work (404s)

我正在尝试使用 node-http-proxy 获得一个非常简单的代理,我希望它只是 return google:

的内容
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 to proxy to http://www.google.co.uk/images/nav_logo242.png 而不是 return 未找到 404。

谢谢。

您需要设置您的请求Host header

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 应用程序中,代理某些请求时可能更容易使用 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 选项 changeOrigin 设置为 true,它将自动在请求中设置 host header。

Vhosted 站点依赖此 host header 才能正常工作。

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
}));