使用 Koa2 提供静态文件

Serve static files with Koa2

当有人访问路由时,如何使用 Koa2 提供静态文件? 我尝试了数百万件事,但总是收到未找到的消息。服务器已响应状态 404

import 'babel-polyfill'
import co from 'co'
import path from 'path'
import render from 'koa-swig'
import Koa from 'koa'
import Router from 'koa-router'
import serve from 'koa-static'
import convert from 'koa-convert'
import send from 'koa-send'

const app: Koa = new Koa()
const route: Routerr = new Router()

**example 1**

app.use(serve(path.resolve(__dirname + '/public/index.html')))

router.get('/lista', function *() {
  console.log('Hello')
})

**example 2**

app.use(async (ctx) => {
  await send(ctx, '/index.html', { root: '/public' })
})

router.get('/lista', function *() {
  console.log('Hello')
})



app.use(router.routes())
app.use(router.allowedMethods())

前段时间我做了一些简单的Koa 2原型应用,基本上就是从模块页面复制示例。不幸的是,这意味着我真的不能告诉你它是如何工作的,但我确实得到了一些东西,它看起来像这样(使用 ES2016):

const serve = require('koa-static');
const mount = require('koa-mount');
const Koa = require('koa');

const static_pages = new Koa();
static_pages.use(serve('static'));

const app = new Koa();
app
    .use(mount('/static', static_pages))

此 "mounts" /static 作为所有静态页面的根,位于本地目录 static.

这与@Some programmer dude 提到的方法类似,但没有使用 mount

import Koa from 'koa';
import serveStatic from 'koa-static';

const app = new Koa();
app.use(serveStatic(__dirname + '/public'));