Nodejs koa2開啓gzip壓縮

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('服務啓動成功');

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章