Browse Source

proxy connection errors no longer crash the server, fixes #37

master
Lloyd Brookes 9 years ago
parent
commit
497653d92e
  1. 6
      bin/cli.js
  2. 1
      example/rewrite/.local-web-server.json
  3. 2
      example/rewrite/index.html
  4. 21
      lib/middleware.js

6
bin/cli.js

@ -62,6 +62,12 @@ if (options.misc.help) {
mocks: options.server.mocks
})
app.on('error', err => {
if (options.server['log-format']) {
console.error(ansi.format(err.message, 'red'))
}
})
if (options.server.https) {
options.server.key = path.resolve(__dirname, '..', 'ssl', '127.0.0.1.key')
options.server.cert = path.resolve(__dirname, '..', 'ssl', '127.0.0.1.crt')

1
example/rewrite/.local-web-server.json

@ -2,6 +2,7 @@
"rewrite": [
{ "from": "/css/*", "to": "/build/styles/$1" },
{ "from": "/npm/*", "to": "http://registry.npmjs.org/$1" },
{ "from": "/broken/*", "to": "http://localhost:9999" },
{ "from": "/:user/repos/:name", "to": "https://api.github.com/repos/:user/:name" }
]
}

2
example/rewrite/index.html

@ -9,6 +9,7 @@
"rewrite": [
{ "from": "/css/*", "to": "/build/styles/$1" },
{ "from": "/npm/*", "to": "http://registry.npmjs.org/$1" },
{ "from": "/broken/*", "to": "http://localhost:9999" },
{ "from": "/:user/repos/:name", "to": "https://api.github.com/repos/:user/:name" }
]
}
@ -18,5 +19,6 @@
<ul>
<li><a href="/css/style.css">/css/style.css</li>
<li><a href="/npm/local-web-server">/npm/local-web-server</a></li>
<li><a href="/broken/">/broken/</a></li>
<li><a href="/75lb/repos/work">/75lb/repos/work</a></li>
</ul>

21
lib/middleware.js

@ -15,14 +15,13 @@ exports.blacklist = blacklist
exports.mockResponses = mockResponses
exports.mime = mime
function proxyRequest (route, app) {
function proxyRequest (route) {
const httpProxy = require('http-proxy')
const proxy = httpProxy.createProxyServer({
changeOrigin: true
})
return function proxyMiddleware () {
const next = arguments[arguments.length - 1]
const keys = []
route.re = pathToRegexp(route.from, keys)
route.new = this.url.replace(route.re, route.to)
@ -33,17 +32,19 @@ function proxyRequest (route, app) {
.replace(re, arguments[index + 1] || '')
})
this.response = false
debug('proxy request', `from: ${this.path}, to: ${url.parse(route.new).href}`)
proxy.once('error', err => {
this.throw(500, `[PROXY] ${err.message}: ${route.new}`)
})
proxy.once('proxyReq', function (proxyReq) {
proxyReq.path = url.parse(route.new).path
return new Promise((resolve, reject) => {
proxy.once('error', err => {
err.message = `[PROXY] Error: ${err.message} Target: ${route.new}`
reject(err)
})
proxy.once('proxyReq', function (proxyReq) {
proxyReq.path = url.parse(route.new).path
})
proxy.once('close', resolve)
proxy.web(this.req, this.res, { target: route.new })
})
proxy.web(this.req, this.res, { target: route.new })
}
}

Loading…
Cancel
Save