http-proxy vs http-proxy-middleware vs express-http-proxy
Node.js HTTP 代理方案选型与架构对比
http-proxyhttp-proxy-middlewareexpress-http-proxy類似套件:

Node.js HTTP 代理方案选型与架构对比

http-proxy 是 Node.js 生态中最基础的 HTTP 代理核心库,提供了底层的代理能力。http-proxy-middleware 是基于 http-proxy 封装的中间件,专为 Connect/Express 等框架设计,广泛用于开发服务器配置。express-http-proxy 则是另一个针对 Express 优化的代理中间件,常用于服务端渲染(SSR)场景中的请求转发。这三者都用于将请求转发到目标服务器,但在抽象层级、使用场景和维护状态上存在显著差异。

npm下載趨勢

3 年

GitHub Stars 排名

統計詳情

套件
下載數
Stars
大小
Issues
發布時間
許可
http-proxy34,254,59414,120-6196 年前MIT
http-proxy-middleware32,354,41211,13197.4 kB158 天前MIT
express-http-proxy753,4971,249150 kB1461 年前MIT

Node.js HTTP 代理方案选型与架构对比

在 Node.js 后端开发或前端工程化构建中,HTTP 代理是一个常见需求。无论是为了在开发环境中转发 API 请求以绕过跨域限制,还是在服务端渲染(SSR)中转发客户端请求到后端服务,我们都需要可靠的代理工具。http-proxy、http-proxy-middleware 和 express-http-proxy 是生态中最常见的三个选择。虽然它们的目标一致,但在设计哲学、集成方式和维护状态上有着本质区别。

🏗️ 核心架构:底层库 vs 中间件封装

理解这三者的关系,首先要分清“核心库”与“中间件”的区别。

http-proxy 是这一切的基础。它是一个纯粹的 Node.js 模块,不依赖任何 Web 框架。它直接操作 HTTP 请求和响应流。

// http-proxy: 独立创建代理服务器
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});

const http = require('http');
const server = http.createServer((req, res) => {
  // 直接代理到目标地址
  proxy.web(req, res, { target: 'http://localhost:3000' });
});

server.listen(8080);

http-proxy-middleware 和 express-http-proxy 都是基于 http-proxy(或类似逻辑)的封装,旨在融入 Connect/Express 的中间件管道。

// http-proxy-middleware: 作为 Express 中间件
const { createProxyMiddleware } = require('http-proxy-middleware');

app.use('/api', createProxyMiddleware({
  target: 'http://localhost:3000',
  changeOrigin: true
}));
// express-http-proxy: 作为 Express 路由处理函数
const proxy = require('express-http-proxy');

app.use('/api', proxy('http://localhost:3000', {
  preserveHostHdr: true
}));

🛠️ 开发体验与配置方式

在配置灵活性和易用性上,这三个包提供了不同的抽象层级。

http-proxy 需要你自己管理服务器实例。这意味着你需要处理路由匹配、错误监听和 WebSocket 升级。

// http-proxy: 手动处理错误和 WebSocket
proxy.on('error', function (err, req, res) {
  res.writeHead(500, { 'Content-Type': 'text/plain' });
  res.end('Something went wrong.');
});

// WebSocket 支持需要单独调用
proxy.ws(req, socket, head, { target: 'ws://localhost:3000' });

http-proxy-middleware 极大地简化了这些配置。它内置了对 WebSocket 的支持,并且配置选项更符合现代开发习惯(如路径重写)。

// http-proxy-middleware: 内置 WebSocket 和路径重写
createProxyMiddleware('/api', {
  target: 'http://localhost:3000',
  ws: true, // 自动代理 WebSocket
  pathRewrite: { '^/api': '' } // 简单配置路径重写
});

express-http-proxy 提供了非常细粒度的控制,特别是针对请求体和用户会话的处理,这在 SSR 场景中很有用。

// express-http-proxy: 精细控制请求用户和 Body
proxy('http://localhost:3000', {
  userResDecorator: function(proxyRes, proxyResData, userReq, userRes) {
    // 可以在响应返回给客户端前修改数据
    return proxyResData;
  },
  proxyReqBodyDecorator: function(bodyContent, srcReq) {
    // 可以修改发送给目标服务器的请求体
    return bodyContent;
  }
});

📦 维护状态与社区生态

这是架构选型中最关键但常被忽视的一点。

http-proxy 是基础设施,非常稳定。虽然更新频率不高,但作为底层库,它的 API 已经固化,极少出现破坏性变更。它是其他两个包的依赖基础。

http-proxy-middleware 是目前社区最活跃的项目。它被广泛集成在 Create React App、Next.js、Vue CLI 等主流脚手架中。如果你遇到文档问题或 Bug,更容易找到解决方案。

express-http-proxy 的维护状态相对较弱。虽然它功能强大,但在近年来的更新频率和社区讨论热度上不如 http-proxy-middleware。在新项目中,除非有特定的 SSR 需求,否则通常建议优先评估更活跃的替代方案。

🔄 路径重写与过滤器

处理 URL 路径映射是代理的常见需求。

http-proxy 没有内置路径重写,你需要手动修改 req.url。

// http-proxy: 手动修改 URL
const server = http.createServer((req, res) => {
  req.url = req.url.replace('/api', ''); // 手动替换
  proxy.web(req, res, { target: 'http://localhost:3000' });
});

http-proxy-middleware 提供了声明式的路径重写配置。

// http-proxy-middleware: 配置式重写
createProxyMiddleware({
  target: 'http://localhost:3000',
  pathRewrite: { '^/api': '/v1' } // 将 /api 替换为 /v1
});

express-http-proxy 允许通过函数动态决定路径。

// express-http-proxy: 函数式路径控制
proxy('http://localhost:3000', {
  proxyReqPathResolver: function (req) {
    return require('url').parse(req.url).path; // 自定义逻辑
  }
});

🛡️ 错误处理与稳定性

在生产环境中,代理服务器的稳定性至关重要。

http-proxy 要求你显式绑定 error 事件,否则进程可能会因为未捕获的异常而崩溃。

// http-proxy: 必须手动绑定错误
proxy.on('error', (err, req, res) => {
  console.error('Proxy error:', err);
  if (!res.headersSent) res.writeHead(500);
  res.end('Proxy Error');
});

http-proxy-middleware 和 express-http-proxy 都在内部处理了大部分常见的错误场景,减少了样板代码。

// http-proxy-middleware: 内置错误处理逻辑
// 如果目标服务器不可达,中间件会自动处理响应或传递错误给下一个中间件
app.use('/api', createProxyMiddleware({ 
  target: 'http://localhost:3000',
  onError: (err, req, res) => {
    res.writeHead(500);
    res.end('Forwarding Error');
  }
}));

📊 总结对比

特性http-proxyhttp-proxy-middlewareexpress-http-proxy
定位底层核心库Express/Connect 中间件Express 专用中间件
框架依赖无Connect/Express 兼容仅 Express
WebSocket需手动调用 .ws()配置 ws: true 自动支持支持
路径重写手动修改 req.url配置 pathRewrite函数 proxyReqPathResolver
维护状态稳定 (基础设施)活跃 (社区标准)一般 (更新较慢)
适用场景独立代理服务器、CLI开发服务器、通用 Web 应用特定 SSR 需求、旧项目

💡 架构师建议

对于大多数现代前端工程化场景(如配置 Webpack Dev Server、Vite 或 Next.js 的自定义服务器),http-proxy-middleware 是标准答案。它平衡了易用性和功能,且社区支持最好。

如果你正在编写一个不依赖 Express 的轻量级 Node.js 服务,或者需要构建一个独立的网关服务,http-proxy 提供了最小的开销和最大的控制权。

对于 express-http-proxy,建议在新项目中谨慎使用。除非你明确需要它在处理 SSR 请求体装饰器(Body Decorator)方面的特定能力,否则 http-proxy-middleware 通常能覆盖 95% 的需求且更易于维护。

如何選擇: http-proxy vs http-proxy-middleware vs express-http-proxy

  • http-proxy:

    选择 http-proxy 当你需要构建自定义的 HTTP 服务器或需要最底层的控制能力时。它不依赖任何 Web 框架,适合编写独立的代理服务器、CLI 工具或需要处理原始 HTTP 流的高级场景。如果你不需要 Express 或 Connect 的中间件管道,这是最轻量且灵活的选择。

  • http-proxy-middleware:

    选择 http-proxy-middleware 如果你的项目基于 Express、Connect 或 Next.js 等使用中间件架构的框架。它是目前社区最活跃、维护最好的方案,特别适合配置本地开发服务器(Dev Server)的路由转发。如果你需要标准的中间件接口和广泛的社区支持,这是首选。

  • express-http-proxy:

    选择 express-http-proxy 仅当你维护旧的 Express 项目且深度依赖其特定的 SSR 转发逻辑时。需要注意的是,该库的维护活跃度相对较低,在新项目中通常建议优先考虑 http-proxy-middleware。它适合需要在 Express 路由中精细控制代理请求体(Body)和头部(Headers)的特定服务端场景。

http-proxy 的 README

node-http-proxy Build Status codecov

node-http-proxy is an HTTP programmable proxying library that supports websockets. It is suitable for implementing components such as reverse proxies and load balancers.

Table of Contents

Installation

npm install http-proxy --save

Back to top

Upgrading from 0.8.x ?

Click here

Back to top

Core Concept

A new proxy is created by calling createProxyServer and passing an options object as argument (valid properties are available here)

var httpProxy = require('http-proxy');

var proxy = httpProxy.createProxyServer(options); // See (†)

†Unless listen(..) is invoked on the object, this does not create a webserver. See below.

An object will be returned with four methods:

  • web req, res, [options] (used for proxying regular HTTP(S) requests)
  • ws req, socket, head, [options] (used for proxying WS(S) requests)
  • listen port (a function that wraps the object in a webserver, for your convenience)
  • close [callback] (a function that closes the inner webserver and stops listening on given port)

It is then possible to proxy requests by calling these functions

http.createServer(function(req, res) {
  proxy.web(req, res, { target: 'http://mytarget.com:8080' });
});

Errors can be listened on either using the Event Emitter API

proxy.on('error', function(e) {
  ...
});

or using the callback API

proxy.web(req, res, { target: 'http://mytarget.com:8080' }, function(e) { ... });

When a request is proxied it follows two different pipelines (available here) which apply transformations to both the req and res object. The first pipeline (incoming) is responsible for the creation and manipulation of the stream that connects your client to the target. The second pipeline (outgoing) is responsible for the creation and manipulation of the stream that, from your target, returns data to the client.

Back to top

Use Cases

Setup a basic stand-alone proxy server

var http = require('http'),
    httpProxy = require('http-proxy');
//
// Create your proxy server and set the target in the options.
//
httpProxy.createProxyServer({target:'http://localhost:9000'}).listen(8000); // See (†)

//
// Create your target server
//
http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.write('request successfully proxied!' + '\n' + JSON.stringify(req.headers, true, 2));
  res.end();
}).listen(9000);

†Invoking listen(..) triggers the creation of a web server. Otherwise, just the proxy instance is created.

Back to top

Setup a stand-alone proxy server with custom server logic

This example shows how you can proxy a request using your own HTTP server and also you can put your own logic to handle the request.

var http = require('http'),
    httpProxy = require('http-proxy');

//
// Create a proxy server with custom application logic
//
var proxy = httpProxy.createProxyServer({});

//
// Create your custom server and just call `proxy.web()` to proxy
// a web request to the target passed in the options
// also you can use `proxy.ws()` to proxy a websockets request
//
var server = http.createServer(function(req, res) {
  // You can define here your custom logic to handle the request
  // and then proxy the request.
  proxy.web(req, res, { target: 'http://127.0.0.1:5050' });
});

console.log("listening on port 5050")
server.listen(5050);

Back to top

Setup a stand-alone proxy server with proxy request header re-writing

This example shows how you can proxy a request using your own HTTP server that modifies the outgoing proxy request by adding a special header.

var http = require('http'),
    httpProxy = require('http-proxy');

//
// Create a proxy server with custom application logic
//
var proxy = httpProxy.createProxyServer({});

// To modify the proxy connection before data is sent, you can listen
// for the 'proxyReq' event. When the event is fired, you will receive
// the following arguments:
// (http.ClientRequest proxyReq, http.IncomingMessage req,
//  http.ServerResponse res, Object options). This mechanism is useful when
// you need to modify the proxy request before the proxy connection
// is made to the target.
//
proxy.on('proxyReq', function(proxyReq, req, res, options) {
  proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
});

var server = http.createServer(function(req, res) {
  // You can define here your custom logic to handle the request
  // and then proxy the request.
  proxy.web(req, res, {
    target: 'http://127.0.0.1:5050'
  });
});

console.log("listening on port 5050")
server.listen(5050);

Back to top

Modify a response from a proxied server

Sometimes when you have received a HTML/XML document from the server of origin you would like to modify it before forwarding it on.

Harmon allows you to do this in a streaming style so as to keep the pressure on the proxy to a minimum.

Back to top

Setup a stand-alone proxy server with latency

var http = require('http'),
    httpProxy = require('http-proxy');

//
// Create a proxy server with latency
//
var proxy = httpProxy.createProxyServer();

//
// Create your server that makes an operation that waits a while
// and then proxies the request
//
http.createServer(function (req, res) {
  // This simulates an operation that takes 500ms to execute
  setTimeout(function () {
    proxy.web(req, res, {
      target: 'http://localhost:9008'
    });
  }, 500);
}).listen(8008);

//
// Create your target server
//
http.createServer(function (req, res) {
  res.writeHead(200, { 'Content-Type': 'text/plain' });
  res.write('request successfully proxied to: ' + req.url + '\n' + JSON.stringify(req.headers, true, 2));
  res.end();
}).listen(9008);

Back to top

Using HTTPS

You can activate the validation of a secure SSL certificate to the target connection (avoid self-signed certs), just set secure: true in the options.

HTTPS -> HTTP
//
// Create the HTTPS proxy server in front of a HTTP server
//
httpProxy.createServer({
  target: {
    host: 'localhost',
    port: 9009
  },
  ssl: {
    key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
    cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
  }
}).listen(8009);
HTTPS -> HTTPS
//
// Create the proxy server listening on port 443
//
httpProxy.createServer({
  ssl: {
    key: fs.readFileSync('valid-ssl-key.pem', 'utf8'),
    cert: fs.readFileSync('valid-ssl-cert.pem', 'utf8')
  },
  target: 'https://localhost:9010',
  secure: true // Depends on your needs, could be false.
}).listen(443);
HTTP -> HTTPS (using a PKCS12 client certificate)
//
// Create an HTTP proxy server with an HTTPS target
//
httpProxy.createProxyServer({
  target: {
    protocol: 'https:',
    host: 'my-domain-name',
    port: 443,
    pfx: fs.readFileSync('path/to/certificate.p12'),
    passphrase: 'password',
  },
  changeOrigin: true,
}).listen(8000);

Back to top

Proxying WebSockets

You can activate the websocket support for the proxy using ws:true in the options.

//
// Create a proxy server for websockets
//
httpProxy.createServer({
  target: 'ws://localhost:9014',
  ws: true
}).listen(8014);

Also you can proxy the websocket requests just calling the ws(req, socket, head) method.

//
// Setup our server to proxy standard HTTP requests
//
var proxy = new httpProxy.createProxyServer({
  target: {
    host: 'localhost',
    port: 9015
  }
});
var proxyServer = http.createServer(function (req, res) {
  proxy.web(req, res);
});

//
// Listen to the `upgrade` event and proxy the
// WebSocket requests as well.
//
proxyServer.on('upgrade', function (req, socket, head) {
  proxy.ws(req, socket, head);
});

proxyServer.listen(8015);

Back to top

Options

httpProxy.createProxyServer supports the following options:

  • target: url string to be parsed with the url module

  • forward: url string to be parsed with the url module

  • agent: object to be passed to http(s).request (see Node's https agent and http agent objects)

  • ssl: object to be passed to https.createServer()

  • ws: true/false, if you want to proxy websockets

  • xfwd: true/false, adds x-forward headers

  • secure: true/false, if you want to verify the SSL Certs

  • toProxy: true/false, passes the absolute URL as the path (useful for proxying to proxies)

  • prependPath: true/false, Default: true - specify whether you want to prepend the target's path to the proxy path

  • ignorePath: true/false, Default: false - specify whether you want to ignore the proxy path of the incoming request (note: you will have to append / manually if required).

  • localAddress: Local interface string to bind for outgoing connections

  • changeOrigin: true/false, Default: false - changes the origin of the host header to the target URL

  • preserveHeaderKeyCase: true/false, Default: false - specify whether you want to keep letter case of response header key

  • auth: Basic authentication i.e. 'user:password' to compute an Authorization header.

  • hostRewrite: rewrites the location hostname on (201/301/302/307/308) redirects.

  • autoRewrite: rewrites the location host/port on (201/301/302/307/308) redirects based on requested host/port. Default: false.

  • protocolRewrite: rewrites the location protocol on (201/301/302/307/308) redirects to 'http' or 'https'. Default: null.

  • cookieDomainRewrite: rewrites domain of set-cookie headers. Possible values:

    • false (default): disable cookie rewriting
    • String: new domain, for example cookieDomainRewrite: "new.domain". To remove the domain, use cookieDomainRewrite: "".
    • Object: mapping of domains to new domains, use "*" to match all domains. For example keep one domain unchanged, rewrite one domain and remove other domains:
      cookieDomainRewrite: {
        "unchanged.domain": "unchanged.domain",
        "old.domain": "new.domain",
        "*": ""
      }
      
  • cookiePathRewrite: rewrites path of set-cookie headers. Possible values:

    • false (default): disable cookie rewriting
    • String: new path, for example cookiePathRewrite: "/newPath/". To remove the path, use cookiePathRewrite: "". To set path to root use cookiePathRewrite: "/".
    • Object: mapping of paths to new paths, use "*" to match all paths. For example, to keep one path unchanged, rewrite one path and remove other paths:
      cookiePathRewrite: {
        "/unchanged.path/": "/unchanged.path/",
        "/old.path/": "/new.path/",
        "*": ""
      }
      
  • headers: object with extra headers to be added to target requests.

  • proxyTimeout: timeout (in millis) for outgoing proxy requests

  • timeout: timeout (in millis) for incoming requests

  • followRedirects: true/false, Default: false - specify whether you want to follow redirects

  • selfHandleResponse true/false, if set to true, none of the webOutgoing passes are called and it's your responsibility to appropriately return the response by listening and acting on the proxyRes event

  • buffer: stream of data to send as the request body. Maybe you have some middleware that consumes the request stream before proxying it on e.g. If you read the body of a request into a field called 'req.rawbody' you could restream this field in the buffer option:

    'use strict';
    
    const streamify = require('stream-array');
    const HttpProxy = require('http-proxy');
    const proxy = new HttpProxy();
    
    module.exports = (req, res, next) => {
    
      proxy.web(req, res, {
        target: 'http://localhost:4003/',
        buffer: streamify(req.rawBody)
      }, next);
    
    };
    

NOTE: options.ws and options.ssl are optional. options.target and options.forward cannot both be missing

If you are using the proxyServer.listen method, the following options are also applicable:

  • ssl: object to be passed to https.createServer()
  • ws: true/false, if you want to proxy websockets

Back to top

Listening for proxy events

  • error: The error event is emitted if the request to the target fail. We do not do any error handling of messages passed between client and proxy, and messages passed between proxy and target, so it is recommended that you listen on errors and handle them.
  • proxyReq: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to "web" connections
  • proxyReqWs: This event is emitted before the data is sent. It gives you a chance to alter the proxyReq request object. Applies to "websocket" connections
  • proxyRes: This event is emitted if the request to the target got a response.
  • open: This event is emitted once the proxy websocket was created and piped into the target websocket.
  • close: This event is emitted once the proxy websocket was closed.
  • (DEPRECATED) proxySocket: Deprecated in favor of open.
var httpProxy = require('http-proxy');
// Error example
//
// Http Proxy Server with bad target
//
var proxy = httpProxy.createServer({
  target:'http://localhost:9005'
});

proxy.listen(8005);

//
// Listen for the `error` event on `proxy`.
proxy.on('error', function (err, req, res) {
  res.writeHead(500, {
    'Content-Type': 'text/plain'
  });

  res.end('Something went wrong. And we are reporting a custom error message.');
});

//
// Listen for the `proxyRes` event on `proxy`.
//
proxy.on('proxyRes', function (proxyRes, req, res) {
  console.log('RAW Response from the target', JSON.stringify(proxyRes.headers, true, 2));
});

//
// Listen for the `open` event on `proxy`.
//
proxy.on('open', function (proxySocket) {
  // listen for messages coming FROM the target here
  proxySocket.on('data', hybiParseAndLogMessage);
});

//
// Listen for the `close` event on `proxy`.
//
proxy.on('close', function (res, socket, head) {
  // view disconnected websocket connections
  console.log('Client disconnected');
});

Back to top

Shutdown

  • When testing or running server within another program it may be necessary to close the proxy.
  • This will stop the proxy from accepting new connections.
var proxy = new httpProxy.createProxyServer({
  target: {
    host: 'localhost',
    port: 1337
  }
});

proxy.close();

Back to top

Miscellaneous

If you want to handle your own response after receiving the proxyRes, you can do so with selfHandleResponse. As you can see below, if you use this option, you are able to intercept and read the proxyRes but you must also make sure to reply to the res itself otherwise the original client will never receive any data.

Modify response


    var option = {
      target: target,
      selfHandleResponse : true
    };
    proxy.on('proxyRes', function (proxyRes, req, res) {
        var body = [];
        proxyRes.on('data', function (chunk) {
            body.push(chunk);
        });
        proxyRes.on('end', function () {
            body = Buffer.concat(body).toString();
            console.log("res from proxied server:", body);
            res.end("my response to cli");
        });
    });
    proxy.web(req, res, option);


ProxyTable API

A proxy table API is available through this add-on module, which lets you define a set of rules to translate matching routes to target routes that the reverse proxy will talk to.

Test

$ npm test

Logo

Logo created by Diego Pasquali

Back to top

Contributing and Issues

  • Read carefully our Code Of Conduct
  • Search on Google/Github
  • If you can't find anything, open an issue
  • If you feel comfortable about fixing the issue, fork the repo
  • Commit to your local branch (which must be different from master)
  • Submit your Pull Request (be sure to include tests and update documentation)

Back to top

License

The MIT License (MIT)

Copyright (c) 2010 - 2016 Charlie Robbins, Jarrett Cruger & the Contributors.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.