api-explorer
api-explorer copied to clipboard
Improve proxy (for CORS) sample using http-proxy-middleware
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 + '.')
}