1.安装koa-compress中间件
cnpm i koa-compress -S
2.配置koa-compress中间件
const Koa = require('koa');
const app = new Koa();
/* gzip压缩配置 start */
const compress = require('koa-compress');
const options = {
threshold: 1024 //数据超过1kb时压缩
};
app.use(compress(options));
/* gzip压缩配置 end */
app.use(async ctx => {
ctx.type = 'html';
ctx.body =
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
</head>
<body>
<div>hello world</div>
</body>
</html>`;
});
const hostName = '127.0.0.1'; //本地IP
const port = 8888; //端口
app.listen(port, hostName, () => {
console.log(`服务运行在http://${hostName}:${port}`);
});
console.log('服务启动成功');