【问题标题】:Display a static html file with koa.js使用 koa.js 显示静态 html 文件
【发布时间】:2014-07-24 08:14:54
【问题描述】:

我要做的是在调用索引路由(即 localhost:3000)时提供 index.html 文件。

我使用 koa-router 进行路由,所以我的路由是这样的:

app.all("/", function * (next){
    //Send the file here
});

我尝试像这样使用 koa-static:

var serve = require('koa-static');
 app.all("/", function * (next){
        serve("index.html");
    });

但这没有用。然后我尝试使用co-views(我现在把html文件放到public目录下):

var views = require("co-views");
var render = views("public");
app.all("/", function * (next){
    this.status = 200;
    this.body = yield render("index.html");
});

但这没有用。

那么谁能告诉我我必须做什么?

【问题讨论】:

    标签: javascript node.js koa


    【解决方案1】:

    有几种方法可以做到,这里有两种。

    模板引擎

    最简单的方法可能是使用像swigjade 这样的模板引擎来提供文件。

    要安装它:

    npm install -s swig
    

    为了使用共同视图,只需这样做

    var views = require("co-views");
    var render = views("public", { map: { html: 'swig' });
    app.all("/", function * (next){
      this.body = yield render("index");
    }); 
    

    普通文件系统

    或者,如果您不想使用模板引擎,您可以使用普通的 Node File System 库。

    为了能够将它与 yield 一起使用,您必须将函数包装在一个 Promise 中。

    var fs = require('fs');
    
    var readFileThunk = function(src) {
      return new Promise(function (resolve, reject) {
        fs.readFile(src, {'encoding': 'utf8'}, function (err, data) {
          if(err) return reject(err);
          resolve(data);
        });
      });
    }
    
    app.use(router.get('/', function *(){
      this.body = yield readFileThunk(__dirname + '/public/htmlfilename.html');
    }));
    

    另外,请注意,如果您使用 koa-static,并且您将 index.html 放在您的公共文件夹(您链接到 koa-static 的文件夹)中,默认情况下它将在根 url 上提供 index.html 而没有任何代码。这是一个约定。

    【讨论】:

    • @Hugo Dozois,如何提供与 index.html 不同的文件?我已经使用带有文件名 app.html 的 koa-static 作为特定路由的路由中间件,但我仍然得到名为 index.html 的文件。
    • 所以github.com/visionmedia/jade 现在重定向到github.com/pugjs/pug,它至少仍然是一个模板引擎。*EDIT* Jade 已更名为 Pug,所以现在一切都有意义了。
    • 非常好的答案,但是不能直接使用 koa-static 来完成它是相当愚蠢的——我的意思是它必须已经有一些类似的代码。
    【解决方案2】:

    将文件流传递给 koa 主体

    这与上面使用纯文件系统的解决方案非常相似,但它利用了 koa 将可读流作为响应主体传递的能力。所以我们唯一需要做的就是打开一个文件的可读流并将其传递给 koa 上下文主体。在此之前给 koa 一个提示,这是 html 类型的响应。

    import { createReadStream } from 'fs';
    
    public async handle(ctx, next) {
        ctx.type = 'html';
        ctx.body = createReadStream('index.html');
    }
    

    【讨论】:

    • 通常最好解释一个解决方案,而不是仅仅发布一些匿名代码行。你可以阅读How do I write a good answer,也可以阅读Explaining entirely code-based answers
    • 编辑@MassimilianoKraus
    • public 关键字在做什么?
    • public 方法修饰符来自 TypeScript 类定义。这是从我的 TypeScript 代码库复制的示例。 @mLuby
    • 不错,正是我需要的
    【解决方案3】:

    这个呢,使用 koa-static

    app.all("/", async(ctx, next) => 
      serve(`${__dirname}/public`)(
        Object.assign(ctx, { path: 'index.html' }), 
        next)
      );
    

    【讨论】:

      猜你喜欢
      • 2015-12-19
      • 2021-04-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      • 2021-05-30
      • 2013-10-26
      • 2017-05-12
      相关资源
      最近更新 更多