我可以在自定义(例如/ static /)path中使用koa-static服务资产吗?

https://github.com/koajs/static中的文档以及我个人使用koa-static的经验让我相信,你只能从你的应用的根URL中提供文件。

例如:

app.use(serve('./some/dir/')); 

鉴于以上使用serve ,访问文件./some/dir/something.txt的URL将是localhost:3000/something.txt 。 似乎没有办法configuration我的应用程序,以便相同的文件(以及同一目录中的所有其他文件)在localhost:3000/static/something.txt

我是Node和Koa的新手,所以我刚刚开始深入了解这一点,我可能错过了一些非常明显的东西。

我试图用koa-route来达到这个目的:

 app.use(route.get('/static/*'), serve(__dirname + '/some/dir')); 

但在请求/static/something.txt我遇到了以下情况:

  TypeError: Cannot read property 'apply' of undefined at Object.<anonymous> (/Users/me/example/src/node_modules/koa-route/index.js:34:18) at GeneratorFunctionPrototype.next (native) at onFulfilled (/Users/me/example/src/node_modules/koa/node_modules/co/index.js:64:19) at /Users/me/example/src/node_modules/koa/node_modules/co/index.js:53:5 at Object.co (/Users/me/example/src/node_modules/koa/node_modules/co/index.js:49:10) at Object.toPromise (/Users/me/example/src/node_modules/koa/node_modules/co/index.js:117:63) at next (/Users/me/example/src/node_modules/koa/node_modules/co/index.js:98:29) at onFulfilled (/Users/me/example/src/node_modules/koa/node_modules/co/index.js:68:7) at /Users/me/example/src/node_modules/koa/node_modules/co/index.js:53:5 at Object.co (/Users/me/example/src/node_modules/koa/node_modules/co/index.js:49:10) 

要将中间件重定位到应用程序的另一部分,可以使用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本身不支持正则expression式path或参数匹配 。

你可以使用koa-static-folder 。 如果你还有兴趣。

你当然可以。 正如接受的答案所说,诀窍就是使用koa-mount和koa-static。 虽然我不明白他为什么不提供实际的静态文件的例子。 这适用于我(Koa2):

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

这两个文件夹(公共和静态)都在我的项目的根。 但是,第一个是在用户访问/ ,而第二个是在/static 。 就这样。