使用koa.js显示静态html文件 [英] Display a static html file with koa.js
问题描述
我想要做的是在调用索引路由(即localhost:3000)时提供index.html文件。
What I want to do is serve the index.html file when the index route (i.e. localhost:3000) is called.
我使用koa-router进行路由,所以我的路线看起来像这样:
I use koa-router for routing, so my route looks like this:
app.all("/", function * (next){
//Send the file here
});
我试图像这样使用koa-static:
I tried to use koa-static like this:
var serve = require('koa-static');
app.all("/", function * (next){
serve("index.html");
});
但这不起作用。然后我尝试使用合作视图(我现在将html文件放在公共目录中):
But that didn't work. Then I tried to use co-views (I put the html file in the public directory now):
var views = require("co-views");
var render = views("public");
app.all("/", function * (next){
this.status = 200;
this.body = yield render("index.html");
});
但这不起作用。
那么有谁能告诉我我必须做什么?
So can anyone tell me what I have to do?
推荐答案
那么有几种方法可以做到这一点,这里有两个他们。
Well there are a few ways to do it, here's two of them.
最简单的方法可能是使用像 swig 或 jade 提供文件。
The simplest way is probably to use a templating engine like swig or jade to serve the file.
要安装它,请执行以下操作:
To install it do :
npm install -s swig
为了使用合作视图,只需执行
In order to do it with co-views, just do
var views = require("co-views");
var render = views("public", { map: { html: 'swig' });
app.all("/", function * (next){
this.body = yield render("index");
});
纯文件系统
或者如果你不想使用模板引擎,您可以使用普通节点文件系统库。
为了能够将它与yield一起使用,你必须将函数包装在一个promise中。
In order to be able to use it with yield, you have to wrap the function in a 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,而不需要任何代码。这是一个惯例。
Also, note that if you use koa-static, and you put index.html in your public folder (the folder you link to koa-static), it's going to serve index.html by default on the root url without any code. This is a convention.
这篇关于使用koa.js显示静态html文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!