我有一个 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/