Why in the following case does koa-static
fail to work with koa-router
?
const Koa = require("koa")
const serve = require("koa-static")
const Router = require("koa-router")
const app = new Koa()
const router = new Router()
// fails with 404... why?
router.use(serve("public"))
// // this, on the other hand, works
// app.use(serve("public"))
app.use(router.middleware())
app.listen(8080)
// browse to "http://localhost:8080/testfile.txt"
This is essentially how we have stuff configured in our app.
It uses koa-mount
to mount the static file server at a particular root URL. If your static file URLs overlap the namespace of your routes, the static files win.
const Koa = require('koa')
const Router = require('koa-router')
const serve = require('koa-static')
const mount = require('koa-mount')
const app = new Koa()
const router = new Router()
router.get('/public/foobar.txt', (ctx,next) => {
ctx.body = "Ta-Da!"
ctx.status = 200
return;
})
app.use( mount( '/public', serve('./public') ) ) ;
app.use( router.middleware())
app.listen( 8080 ) ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With