简体   繁体   中英

proxy request in node.js / express

I have a nginx server as a front end to a node.js application.
When the request gets to the application, I'd like to slightly modify it (the request) and forward it to another node.js application. What would be the best way to do this?

I was thinking of node-proxy but as I use expressjs in the node apps, I'm not really sure how to use node-proxy and express at the same time.

any idea?

UPDATE

Could I use res.redirect in my expressjs routes to forward to other node.js application? I have just tried this but it does not work as expected.

I use node-http-proxy and express.js at the same time quite successfully. Here's the coffeescript source.

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

Iv'd been working abit on a proxy setup for node.js with express on top, that handelse get, put & post.

This is what i came up with:

var DEVEL_PATH = "https://your-url.com";
var API_PATH = "/your-api-route";

app.use(API_PATH, function(req, res) {
    var url = DEVEL_PATH + API_PATH + req.url;
    if(req.method == "GET") {
        req.pipe(request(url)).pipe(res);
    } else {
        req.pipe(request[req.method.toLowerCase()]({url: url, json: req.body})).pipe(res);
    }
});

This basically just takes care is a get then just request that on another url and pipe that to my response. If its a post/put request grab the body of the request and post that as a JSON object.

Remember!!

You need following:

  1. express
  2. request
  3. body-parser

And they need to be setup, check each of them for setup

res.redirect('http://otherapp.com') should work if you have your other app listening on another port or host/domain name, but the request object may not be passed on as you expect. How are you modifying it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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