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

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

https://github.com/koajs/static 的文档和我尝试 koa-static 的个人经验让我相信你可以只能 从根 URL 提供文件您的应用程序。

例如:

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

鉴于 serve 的上述用法,URL 访问文件 ./some/dir/something.txt 将是 localhost:3000/something.txt。似乎没有办法配置我的应用程序,以便在 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)

要将中间件重新定位到应用程序的另一部分 url,您可以使用 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 本身 does not support regex paths or parameter matching.

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

当然可以。正如公认的答案所说,诀窍是将 koa-mount 与 koa-static 一起使用。虽然我不明白为什么他不提供实际静态文件的示例。这对我有用(在 Koa2 中):

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

两个文件夹(public 和 static)都在我项目的根目录中。但是第一个是在用户访问 / 时提供的,而第二个是在用户访问 /static 时提供的。 就这些了。