我可以在自定义(例如/ static /)路径上拥有koa-static服务资产吗?

oro*_*aki 12 static-files node.js koa

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

例如:

app.use(serve('./some/dir/'));
Run Code Online (Sandbox Code Playgroud)

鉴于以上使用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'));
Run Code Online (Sandbox Code Playgroud)

但在要求时,/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)
Run Code Online (Sandbox Code Playgroud)

Dan*_*try 16

要将中间件重新定位到应用程序的另一部分,您可以使用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'
Run Code Online (Sandbox Code Playgroud)

koa-router本身不支持正则表达式路径或参数匹配.

  • 我试过`app.use(mount('/ static',serve(__ dirname +'/ static')));`(完美地工作)因为koa-compose在很长一段时间内没有更新.我可能会坚持使用第二个应用程序,这样我就可以使用很多中间件. (3认同)

Luc*_*edo 8

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

.use(serve('public'))
.use(mount('/static', serve('static')))
Run Code Online (Sandbox Code Playgroud)

两个文件夹(公共和静态)都在我的项目的根目录中.但是第一个是在用户访问时提供的/,而第二个是在他们访问时提供的/static.就这样.