前言
在使用 Koa 框架搭建网站时,一般返回 index.html 当做入口文件,这需要设置特定的 response header.
由于 Koa 自身极简的设计思想,我相信没看过源码的同学,第一时间会写出如下代码:
const Koa = require("koa");
const fs = require("fs");
const app = new Koa();
app
.use(ctx => {
ctx.set("Content-Type", "text/html");
ctx.body = fs.readFileSync("index.html");
})
.listen(3000);
复制代码
这当然可行,还能加强你对 HTTP Headers 的理解,但真正熟悉 Koa 的人,不屑于用如此原始的方法。
别看 Koa 的源码短小精悍,它依旧为开发者提供了诸多便捷的功能,例如此文着重介绍的 ctx.type.
带你认识 ctx.type
先上代码,只需将上下文(ctx)的 type 设置为 “html” 即可:
app
.use(ctx => {
ctx.type = "html";
ctx.body = fs.readFileSync("index.html");
})
.listen(3000);
复制代码
用 http(没有安装这个命令的小伙伴,访问这个网址:httpie.io/ )在终端进行测试: