1、test.ejs文件
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <% for(var i=0;i<json.arr.length;i++){ %> <div>用户名:<%=json.arr[i].user%> 密码:<%=json.arr[i].pass%></div> <% } %> </body> </html>
2、ejs.js文件
var ejs=require('ejs'); var http = require('http'); ejs.renderFile('cleaning.ejs', {json: {arr: [ {user: '马武', pass: '1269'}, {user: '张三', pass: '7654'}, {user: '王二', pass: '2143'} ]}}, function (err, data){ //创建服务 http.createServer(function(req,res){ res.writeHead(200,{'Content-Type':'text/html'}); res.write(data); res.end('<p>渲染结束</p>'); }).listen(8080,"localhost",function () { console.log("open server at port:8080..."); }); });
3、浏览器直接访问接口8080即可展示页面