如何通过查询网站注册时间,网站怎么修改模板内容,福州模板建站哪家好,手机网站建设制作公司静态服务中间件#xff1a;koa-static
中间件可以决定是否向下执行#xff0c;如果自己可以处理#xff0c;那么直接处理完毕结束#xff0c;如果自己处理不了#xff0c;next 方法会继续向下执行
新建 public 文件夹#xff0c;里面添加 index.html、style.css 文件
…静态服务中间件koa-static
中间件可以决定是否向下执行如果自己可以处理那么直接处理完毕结束如果自己处理不了next 方法会继续向下执行
新建 public 文件夹里面添加 index.html、style.css 文件
!DOCTYPE html
html langenheadmeta charsetUTF-8 /meta nameviewport contentwidthdevice-width, initial-scale1.0 /title凯小默测试静态服务中间件koa-static/titlelink relstylesheet href./style.css //headbodyh1凯小默测试静态服务中间件koa-static/h1/body
/htmlbody {background-color: pink;
}koa-static
npm i koa koa-static用法
const serve require(koa-static);
const Koa require(koa);
const app new Koa();// $ GET /package.json
app.use(serve(.));// $ GET /hello.txt
app.use(serve(test/fixtures));// or use absolute paths
app.use(serve(__dirname /test/fixtures));app.listen(3000);console.log(listening on port 3000);业务代码 static.js 中使用 koa-static
const Koa require(koa);
const path require(path);
const bodyParser require(koa-bodyparser);
// 使用自己实现的中间件
// const static require(koa-static);
const static require(./kaimo-koa-static);
const app new Koa();
app.use(bodyParser());
app.use(static(__dirname));
app.use(static(path.resolve(__dirname, public)));app.use((ctx, next) {console.log(ctx.path, ctx.method);if (ctx.path /login ctx.method GET) {ctx.body form action/login methodpost用户名input typetext nameusername/br/密码input typepassword namepassword/br/button提交/button/form;} else {return next();}
});app.use(async (ctx, next) {console.log(ctx.path, ctx.method);if (ctx.path /login ctx.method POST) {ctx.body ctx.request.body;} else {await next();}
});app.on(error, function (err) {console.log(error-----, err);
});app.listen(3000);启动服务访问 http://localhost:3000/index.html nodemon static.js下面实现自己的 koa-static需要安装 mime
const path require(path);
const fs require(fs).promises;
const mime require(mime);console.log(使用的是 kaimo-koa-static 中间件);
module.exports function static(root) {return async (ctx, next) {let filePath path.join(root, ctx.path);try {let statObj await fs.stat(filePath);// 判断是否是文件if (statObj.isFile()) {ctx.type mime.getType(filePath) ;charsetutf-8;ctx.body await fs.readFile(filePath);} else {await next();}} catch (e) {await next();}};
};