node.js - node.js/express 中的代理请求

标签 node.js proxy

我有一个 nginx 服务器作为 node.js 应用程序的前端。
当请求到达应用程序时,我想稍微修改它(请求)并将其转发给另一个 node.js 应用程序。执行此操作的最佳方法是什么?

我在考虑 Node 代理,但是当我在 Node 应用程序中使用 expressjs 时,我不太确定如何同时使用 Node 代理和 express。

有什么想法吗?

更新

我可以在我的 expressjs 路由中使用 res.redirect 来转发到其他 node.js 应用程序吗?我刚刚试过这个,但它没有按预期工作。

最佳答案

我使用 node-http-proxy和 express.js 同时非常成功。这是 coffeescript 源代码。

querystring = require 'querystring'
httpProxy = require 'http-proxy'

#Your express setup code would be here
#omitted for brevity....

proxy = new httpProxy.HttpProxy()

#1. Whatever HTTP Methods and URL paths you want to modify and forward
app.all '/foo/*', (req, res) ->
  #2. Your logic to modify the request goes here
  #Note there are limitations to what you can do.
  #I add some extra query parameters to the URL
  query = if '?' in req.url then '&' else '?'
  params =
    extra1: 'foo'
    extra2: 'bar'
  req.url = [
    req.url
    query
    querystring.stringify params
  ].join ''
  #3. The host and port could also be pulled from the req object if needed
  proxy.proxyRequest req, res,
    host: 'somehost.example'
    port: 80

关于node.js - node.js/express 中的代理请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7075577/

相关文章:

node.js - 将可写 Node 流合并为一个流

node.js - 使用 axios、Node.js 连接到 Azure Blob 存储 REST API

c - 在代理中,在将浏览器请求发送到主机之前对其进行格式化

ubuntu - 具有自动启动功能的应用服务器上的 RethinkDB 代理

websocket - 实现对 HTTP/2 代理的 websocket 支持

javascript - JSON.stringify(array) 用方括号包围

node.js - 大多数准系统 MongoDB Express.js 应用程序

javascript - 使用 Websockets 对 Vue.js/Node.js 应用程序进行单元测试

proxy - HTTPS over Socks5 服务器实现

javascript - insertBefore 代理元素 : parameter 2 is not of type 'Node'