【问题标题】:Serve static files with Koa2使用 Koa2 提供静态文件
【发布时间】:2017-03-14 19:00:39
【问题描述】:

当有人访问路由时,如何使用 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())

【问题讨论】:

    标签: reactjs koa koa2


    【解决方案1】:

    不久前我做了一些简单的 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))
    

    此“挂载”/static 作为所有静态页面的根目录,这些页面位于本地目录static

    【讨论】:

      【解决方案2】:

      这是@Some程序员老兄提到的类似方法,但不使用mount

      import Koa from 'koa';
      import serveStatic from 'koa-static';
      
      const app = new Koa();
      app.use(serveStatic(__dirname + '/public'));
      

      【讨论】:

        猜你喜欢
        • 2013-10-17
        • 2011-01-27
        • 2015-03-04
        • 2012-08-20
        • 2019-01-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多