villadora / express-http-proxy

Proxy middleware for express/connect
Other
1.22k stars 237 forks source link

Body is not added to the request #226

Open FrancescoSaverioZuppichini opened 7 years ago

FrancescoSaverioZuppichini commented 7 years ago

The body of a request doesn't reach the proxed server.

monkpow commented 7 years ago

@FrancescoSaverioZuppichini Can you give more information please? Sounds like a serious bug. Can you tell me more about the case where the body of the request doesn't reach the proxied server?

Thanks!

FrancescoSaverioZuppichini commented 7 years ago

I have the following code:

// set up each proxy entry
for (let key in config) {
  app.use(`/${key}/*`, proxy(config[key], {
    proxyReqPathResolver: (req) => { return config[key] + req.originalUrl.split(key)[1] }
  }))
}

Where config is my file with all the ips:

  'transport': 'http://localhost:8080',
  'auth': 'http://localhost:8081',
  'classes': 'http://localhost:8082',
  'user+display': 'http://localhost:8083'
}

No body is passed to my servers, so I had to implement it by myself by doing


for (let key in config) {
  app.use(`/${key}/api*`, (req, res) => {
    axios({
        method: req.method,
        url: config[key] + req.originalUrl.split(key)[1],
        data: req.body
      })
      .then((data) => {
        res.send(data.data)
      })
      .catch((err) => {
        res.send(err.data)
      })
  })
}```
bitsal commented 7 years ago

@FrancescoSaverioZuppichini could you verify whether you use any body parsers in your proxy configuration above? I had a similar issue when I have invalid body parser configured above.

FrancescoSaverioZuppichini commented 7 years ago

This is my cofing

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
bitsal commented 7 years ago

Everything works with devServer.use(bodyParser.urlencoded()); only. I didn't play with extra options but with a combination of parsers and default settings, it doesn't work for me as well.

Try to play with parsers as a workaround solution: e.g. specify specific URLs (regexp) for a particular parser if you know what content type is used for which.

The final solution/cause should be explained by contributors.

P.S.: Try to change the order of your parsers, because a string like "field1=val1&field2=va2" is a valid JSON as a string.

FrancescoSaverioZuppichini commented 7 years ago

it's working! Thank you

bitsal commented 7 years ago

@FrancescoSaverioZuppichini I wonder what has helped you finally

jamesabc commented 6 years ago

I had this issue when adding a body to a request that was originally empty. Adding the missing header

proxyReqOpts.headers['Content-Type'] = 'application/json';

in proxyReqOptDecorator was the solution