Skip to content
This repository has been archived by the owner on Mar 20, 2023. It is now read-only.

Improve proxy (for CORS) sample using http-proxy-middleware #145

Open
cguedes opened this issue Sep 20, 2016 · 0 comments
Open

Improve proxy (for CORS) sample using http-proxy-middleware #145

cguedes opened this issue Sep 20, 2016 · 0 comments

Comments

@cguedes
Copy link
Contributor

cguedes commented Sep 20, 2016

The existing samples of API Explorer server uses a buggy implementation for proxy the requests.

I propose to use https://github.com/chimurai/http-proxy-middleware to proxy request to the target server.

Sample implementation:

app.use('/proxy', proxy({
  logLevel: 'info',
  target: 'http://localhost',
  router: function (req) {
    // SAMPLE REQUEST: /proxy?url=http%3A%2F%2Flocalhost%3A7000%2Fapi-docs%3Ffoo%3D1%26bar%3D42
    const url = req.query.url
    // console.log('URL: ', url)
    const urlModule = require('url')
    const urlObject = urlModule.parse(url)
    // console.log(urlObject)
    const target = `${urlObject.protocol}//${urlObject.host}`
    // console.log('TARGET:', target)
    return target
  },
  pathRewrite: function (path, req) {
    // console.log()
    // SAMPLE REQUEST: /proxy?url=http%3A%2F%2Flocalhost%3A7000%2Fapi-docs%3Ffoo%3D1%26bar%3D42
    // SAMPLE REQUEST (url decoded): http://localhost:3002/proxy?url=http://localhost:7000/api-docs
      // console.log('REWRITE URL: ', req.query.url)
      const urlModule = require('url')
      const urlObject = urlModule.parse(req.query.url)
      // console.log('REWRITE PATH', urlObject.path)
      return urlObject.path
  },
  changeOrigin: true,
  onError: onProxyError
}))

function onProxyError (err, req, res){
  var host = req.headers && req.headers.host
  console.log(chalk.red('Proxy error:') + ' Could not proxy request ' + chalk.cyan(req.url))
  console.log()
  // And immediately send the proper error response to the client.
  // Otherwise, the request will eventually timeout with ERR_EMPTY_RESPONSE on the client side.
  if (res.writeHead && !res.headersSent) {
      res.writeHead(500);
  }
  res.end('Proxy error: Could not proxy request ' + req.url + '.')
}
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants