1.下载安装
cnpm install ejs --save
2.模板
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>EJS 模板引擎</title>
</head>
<body>
<h3><%= msg %></h3>
<br>
<ul>
<!--for循环-->
<% news.forEach(function(data){ %>
<li><%=data.title%></li>
<% }); %>
</ul>
</body>
</html>
3.渲染
const http = require("http");
const url = require("url");
const ejs = require('ejs');
http.createServer(function(request, response){
let pathName = url.parse(request.url).pathname;
let list = [
{
title: 'news1'
},
{
title: 'news2'
},
{
title: 'news3'
},
{
title: 'news4'
},
{
title: 'news5'
},
{
title: 'news6'
}
]
let text = '';
if (pathName == '/login'){
let text = "欢迎登录!"
ejs.renderFile('./views/login.ejs', {
'msg': text,
'news': list
}, {}, function(err, content){
response.writeHead(200, {"Content-Type": "text/html;charset=utf-8"});
response.end(content);
})
} else {
response.writeHead(404, {"Content-Type": "text/plain;charset=utf-8"});
response.end("页面不存在");
}
}).listen(8081);
console.log('Server runnng at http://127.0.0.1:8081/');
4.Get、Post
1.获取GET传值
var urlinfo = urlparse(req, true);
var body = urlinfo.query;
2.获取POST传值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录</title>
</head>
<body>
<form action="/doLogin" method="post">
用户名:<input type="text", name="username" /><br>
密码:<input type="password", name="password" /><br>
<input type="submit", value="提交">
</form>
</body>
</html>
const http = require("http");
const url = require("url");
const ejs = require('ejs');
const querystring = require('querystring');
http.createServer(function(request, response){
if (pathName == '/login'){
ejs.renderFile('./views/form.ejs', {}, function(err, content){
response.writeHead(200, {"Content-Type": "text/html;charset=utf-8"});
response.end(content);
})
} else if (pathName == '/doLogin'){
let postData = "";
request.on('data', function(chunk){
postData += chunk
});
request.on('end', function(){
console.log(querystring.parse(postData));
response.end("post ok");
} else {
response.writeHead(404, {"Content-Type": "text/plain;charset=utf-8"});
response.end("页面不存在");
}
}).listen(8081);
console.log('Server runnng at http://127.0.0.1:8081/');