安装
npm install koa-static 测试版本:5.0.0 参数说明: static(path, options) path 字符串 指定资源文件根目录 options 可选 对象 相关选项 options相关属性: maxage 默认0,浏览器缓存最大时间,单位毫秒 hidden 默认false,允许传输隐藏文件 index 默认index.html,文件名 defer 默认false,true:在next()后,允许下游中间件首先响应 gzip 默认true,如果请求文件带有gzip,则尝试自动提供gzip版本文件 extensions 默认false,当url中没有足够的扩展名时,尝试匹配传递数组中的扩展以搜索文件 setHeaders 自定义相应header内容
用法
HTML: 路径:./views/index.ejs <!DOCTYPE html> <html> <head> <meta charset="utf8"/> <title><%=title%></title> <!--资源文件,注意路径是./static下文件--> <link rel="icon" type="image/png" href="favicon.png"> <link rel="stylesheet" type="text/css" href="index.css"> </head> <body> <input type="button" id="bcss" value="测试CSS"/> </body> </html> 资源文件目录: 路径:根目录 ./static/ image: favicon.png index.css: #bcss{ width:100px; height:30px; background-color:aqua; border:none; } 服务器:index.js const ejs = require("koa-ejs"); //HTML渲染 const static = require("koa-static"); //静态文件管理 const koa = require("koa"); var app = new koa(); app.listen(8080,"localhost",()=>{ console.log("开始监听"); }); //设置前端HTML文件目录,及后缀名 //设前端文件目录:根目录 ./views/ ejs(app,{ root:path.resolve(__dirname, "views"), //模板ejs文件目录 layout:false, viewExt:"ejs", //HTML文件扩展名 cache:false, debug:false //终端调试 }); //资源文件管理目录,存放前端js、css、image、favicon.png //设资源文件目录:根目录 ./static/ app.use(static("./static")); app.use(async ctx => { if(ctx.path == "/index"){ await ctx.render("index",{ //ejs文件名,不带后缀 //传到HTML中的变量 title:"liboke.cn" }); } });