Can I have koa-static serve assets at a custom (e.g., /static/) path?

℡╲_俬逩灬. 提交于 2019-12-03 11:07:55

To relocate middleware to another part of your app url-wise, you can use koa-mount.

'use strict';
const koa = require('koa');
const mount = require('koa-mount');

const app = koa();
app.use(function* () { this.body = 'Hello, world'; });
app.use(mount('/foo', function*() { this.body = 'Hello, foo'; }));

app.listen(3000);

curl localhost:3000
> 'Hello, world'
curl localhost:3000/foo
> 'Hello, foo'

koa-router itself does not support regex paths or parameter matching.

Sure you can. And as the accepted answer says, the trick is using koa-mount along with koa-static. Though I don't understand why he doesn't provide an example with actual static files. This works for me (in Koa2):

.use(serve('public'))
.use(mount('/static', serve('static')))

Both folders (public and static) are in my project's root. But the first one is served when the user access to /, whereas the second one is served when they go to /static. That's all.

Rei Dien

you can use koa-static-folder. if you're still interested.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!