安装ejs
代码语言:javascript复制npm install ejs
项目引入
代码语言:javascript复制const ejs = require('ejs')
目录文件
app.js
代码语言:javascript复制const http = require('http');
const url = require('url')
const ejs = require('ejs')
http.createServer((req, res) => {
// 路由
let pathname = url.parse(req.url).pathname;
if (pathname == '/login') {
// 假设定义从服务器请求的数据
let msg = "数据库里面获取的数据"
let list = [{
title: '新闻111'
}, {
title: '新闻222'
}, {
title: '新闻333'
}, ]
ejs.renderFile('./views/login.ejs', {
msg: msg,
list: list
}, (err, data) => {
res.writeHead(200, {
'Content-Type': 'text/html;charset="utf-8"'
});
res.end(data)
})
}
}).listen(8081);
login.ejs
代码语言:javascript复制<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h3><%=msg%></h3>
<ul>
<%for(let i in list) {%>
<li><%= list[i].title%></li>
<%}%>
</ul>
</body>
</html>