Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

How to modify the body of a request before proxying #442

Open
micheltem opened this Issue · 0 comments

1 participant

@micheltem

Hi,
I need to modify a request body before proxying to another server.
So far, I managed to make it almost work perfectly using the bodyParser and connect-restreamer modules, but the changes made to the req.body are lost on proxying as in the example below.

Basically the req coming from A has the attributes x, y & z. I need to remove z, change the value of y and and add w so that the end server B to which I am proxying will have x, y*, w.

I added a middleware that does the job of modifying the body and req.url. However when the request is proxied through, it seems like the modifications to the body are always lost as if it posts the original body, not the final one (or is the req.body read-only?). The changes to other properties such as req.url are being proxied correctly.

Is there another way to accomplish this? What am I doing wrong? If req.body is read-only in node-http-proxy, how would you accomplish this?

Thanks for the help

... my current code

http = require("http")
httpProxy = require("http-proxy")
bodyParser = require("connect/lib/middleware/bodyParser")
express = require('express')

# the endpoint server to which I am proxying
app = express.createServer()
app.use(express.bodyParser())
app.all '*', (req, res) ->
    console.log "\n\nServing request for: #{req.url}" # the url has changed
    console.log ">>> Body: "
    _body = JSON.stringify req.body
    console.log _body # the w prop is NOT there
    res.send _body

app.listen "3063", ->
    console.log "Started endpoint server on 3063..."

bodyModifier = () ->
    (req, res, next) ->
        # changing the req.body and req.url
        req.body.w = 'a new property'
        console.dir req.body # the w prop is there
        req.url = "/a_new_url" # the url is changed
        next()

httpProxy.createServer(
    bodyParser(),
    bodyModifier(),
    require("connect-restreamer")()
    , (req, res, proxy) ->
        console.log "Redirecting for url: #{req.url} with body:" # the url has been changed
        console.dir req.body # the w prop is there
        proxy.proxyRequest req, res,
            host: "localhost.mysite.com"
            port: port

).listen 3060, ->
    console.log "Started Proxy server on port 3060..."

# then test with
# $ curl localhost.mysite.com:3060 -X POST -d 'x=oh&y=my&z=gosh'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.