用法
HTML: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"/> <form action='form1' method='post'> <input type='text' name='name' /> <input type='submit' value='提交' /> </form> </body> </html> CSS:index.css #bcss{ width:100px; height:30px; background-color:aqua; border:none; } 后端:index.js var ejs = require("koa-ejs"); //HTML渲染 var static = require("koa-static"); //静态文件管理 var path = require("path"); var koa = require("koa"); var app = new koa(); app.listen(8080,"localhost",()=>{ console.log("开始监听"); }); ejs(app,{ root:path.resolve(__dirname,"views"), //模板ejs文件目录 layout:false, viewExt:"ejs", //视图文件扩展名 cache:false, debug:false //终端调试 }); app.use(static("./static")); app.use(async ctx => { //console.log(ctx.path); if(ctx.method == "GET"){ if(ctx.path == "/"){ //是首页 await ctx.render("index",{ //解析ejs文件名,并发送到客户端 //传到HTML中的变量 title:"liboke.cn" }); } }else if(ctx.method == "POST"){ if(ctx.path == "/form1"){ //请求表单 ctx.req.on("data", function(data){ //使用node原生方法,获取POST数据 ctx.body=data.toString(); //发送字符串到客户端 }); } } }); 测试结果:
![]()