nodejs基于ejs的一个简单demo

1文件大概目录

2.建立项目文件,先建一个ejs_demo文件夹,在ejs_demo运行下面命令,初始化仓库,一路回车:

npm init

3.安装两个ejs和express插件:

npm install ejs --save
npm install express --save

4.建立文件app.js,写上以下代码:

var http=require("http");
var express=require("express");
var app=express();
var path = require('path');
// 1.在app.js的头上定义ejs:
var ejs = require('ejs');
//定义变量
var tem={
  message:"我是中间部分"
};
//创建服务器
//在控制台输入node app.js启动服务器
http.createServer(app).listen(8080,function(){
  console.log("服务器地址为:http://localhost:8080");
});
//挂载静态资源处理中间件,设置css或者js引用文件的静态路径
app.use(express.static(__dirname+"/public"));
// 或者以下这个也可以
// app.use(express.static(path.join(__dirname, 'public'), {maxAge: 36000}));
//设置模板视图的目录
app.set("views","./public/views");
//设置是否启用视图编译缓存,启用将加快服务器执行效率
app.set("view cache",true);
// 2.注册html模板引擎:
app.engine('html',ejs.__express);
//设置模板引擎的格式即运用何种模板引擎
app.set("view engine","html");
//设置路由
app.get("/index",function(req,res){
  res.render("index",{title:tem.message});
});

5.写index.html文件

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <title>EJS</title>
    <meta name="description" content="">
    <meta name="keywords" content="">
    <link href="/css/main.css" rel="stylesheet">
</head>
<body>
<%- include("./header.html") %>
<h1><%=title%></h1>
<%- include("./footer.html") %>
</body>
</html>

6.写header.html文件:

<!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>
   <h1>我是头部</h1>
</body>
</html>

7.写footer.html文件:

<!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>
    <h1>我是尾部</h1>
</body>
</html>

8.写main.css文件:

h1{
  width:80%;
  height:100px;
  background:green;
  margin:20px auto;
  text-align: center;
  line-height:100px;

}

9.在ejs_demo文件夹下运行以下命令:

node app.js

10.在浏览器输入以下域名:

http://localhost:8080/index

11.最后效果图:

猜你喜欢

转载自blog.csdn.net/qq_39634880/article/details/83377909