我们在项目里建立一个views文件夹(必须),如果你不想使用views文件夹的话需要调用app.set("views","自定义文件夹名"),然后在里面建立一个模板文件news.ejs:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<ul>
<% for(var i = 0;i<news.length;i++){%>
<li><%=news[i]%></li>
<%}%>
</ul>
</body>
</html>
然后js文件里绑定渲染关系:
var express = require("express");
var app = express(); app.set("view engine","ejs");
app.get("/",function (req,res) {
res.render("news",{
"news":["新闻1","新闻2","新闻3"]
})
}).listen();
然后启动服务,访问3000端口,页面输出: