Browse Source

rollback to koa-route@^2

master
Lloyd Brookes 9 years ago
parent
commit
5983bacc23
  1. 2
      example/spa/css/style.css
  2. 4
      example/spa/index.html
  3. 17
      lib/local-web-server.js
  4. 2
      package.json

2
example/spa/css/style.css

@ -1,3 +1,5 @@
body {
background-color: IndianRed;
}
a { color: black }

4
example/spa/index.html

@ -3,6 +3,10 @@
</head>
<h1>Single Page App</h1>
<h2>Location: <span></span></h2>
<ul>
<li><a href="/login">/login</a></li>
<li><a href="/search">/search</a></li>
</ul>
<script>
document.querySelector('h2 span').textContent = window.location.pathname
</script>

17
lib/local-web-server.js

@ -34,6 +34,7 @@ function localWebServer (options) {
options = Object.assign({
static: {},
serveIndex: {},
spa: null,
log: {},
compress: false,
mime: {},
@ -129,7 +130,7 @@ function localWebServer (options) {
if (options.spa) {
const send = require('koa-send')
app.use(_.all('*', function * () {
yield send(this, options.spa, { root: process.cwd() })
yield send(this, options.spa, { root: options.static.root || process.cwd() })
}))
}
return app
@ -146,35 +147,35 @@ function proxyRequest (route) {
changeOrigin: true
})
return function proxyMiddleware (ctx) {
return function * proxyMiddleware () {
const next = arguments[arguments.length - 1]
const keys = []
route.re = pathToRegexp(route.from, keys)
route.new = ctx.path.replace(route.re, route.to)
route.new = this.path.replace(route.re, route.to)
keys.forEach((key, index) => {
const re = RegExp(`:${key.name}`, 'g')
route.new = route.new
.replace(re, arguments[index + 1] || '')
.replace(re, arguments[index] || '')
})
/* test no keys remain in the new path */
keys.length = 0
pathToRegexp(route.new, keys)
if (keys.length) {
ctx.throw(500, `[PROXY] Invalid target URL: ${route.new}`)
this.throw(500, `[PROXY] Invalid target URL: ${route.new}`)
return next()
}
ctx.response = false
this.response = false
proxy.once('error', err => {
ctx.throw(500, `[PROXY] ${err.message}: ${route.new}`)
this.throw(500, `[PROXY] ${err.message}: ${route.new}`)
})
proxy.once('proxyReq', function (proxyReq) {
proxyReq.path = url.parse(route.new).path;
})
proxy.web(ctx.req, ctx.res, { target: route.new })
proxy.web(this.req, this.res, { target: route.new })
}
}

2
package.json

@ -40,7 +40,7 @@
"koa-etag": "^2.1.0",
"koa-morgan": "^0.4.0",
"koa-rewrite": "^1.1.1",
"koa-route": "^3",
"koa-route": "^2.4.2",
"koa-send": "^3.1.0",
"koa-serve-index": "^1.1.0",
"koa-static": "^1.5.2",

Loading…
Cancel
Save