服務器渲染頁面 ejscss
高效的 js 模版引擎html
將數據提早渲染到頁面上, 再將渲染好的頁面返回響應給瀏覽器node
提升首頁加載速度mongodb
SEO 提早處理,提升加載速度數據庫
npm install ejsexpress
無需引用,可是要配置模板資源目錄npm
// app.set('views', '模板資源目錄');json
app.set('views', 'views'); // 一般文件夾 也叫 viewspromise
1. 配置模板資源目錄 ( Router 沒有 set 方法,因此必須在 主模塊下 app.set() )瀏覽器
app.set('views', 'views'); // 一般文件夾 也叫 views
2. 配置要使用的模板引擎 ( Router 沒有 set 方法,因此必須在 主模塊下 app.set() )
app.set('views engine', 'ejs');
3. 將 後臺數據 渲染到 模板資源 上
app.get('/ejs', (request, response)=>{ const data = [{ "name": '孫悟空'. "age": 555 },{
"name": '白骨精',
"age": 18
}]; response.render('test.ejs', {data}); // .ejs 能夠省略 });
4. views/test.ejs
模板語法
1. <% %> 其中能夠寫任意 js 代碼
2. <%= %>
3. <%- %>
源碼測試
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
</head>
<body>
<% console.log("哈哈"); %> 不會顯示到頁面上 <%= data[0].name %> 輸出指定數據到頁面上 不會解析標籤,轉義 HTML 相關源碼後輸出
安全性更高 <%- data[1].name %> 輸出指定數據到頁面上 解析 HTML 源碼 通常結合使用: <% for(var i=0; i<10; i++){ %> <%= data[i].name %> <% }; %>
</body>
</html>
凡是通過用戶輸入的東西,都須要進行特殊處理。
package.json
{ "name": "node_express", "version": "1.0.0", "main": "index.js", "license": "MIT", "dependencies": { "connect-mongo": "^2.0.3", "ejs": "^2.6.1", "express": "^4.16.4", "mongoose": "^5.4.0", "sha1": "^1.1.1" } }
public/register.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>用戶註冊</title>
<link rel="stylesheet" type="text/css" href="css/index.css"/>
</head>
<body>
<div id="outer_box" class="register">
<h2>用戶註冊</h2>
<form action="http://localhost:3000/register" method="post">
<div class="clothes">
<label for="input_name">用 戶 名</label>
<input id="input_name" type="text" name="user_name" placeholder="請輸入用戶名" />
</div>
<div class="clothes">
<label for="input_pwd">密 碼</label>
<input id="input_pwd" type="password" name="user_pwd" placeholder="請輸入密碼" />
</div>
<div class="clothes">
<label for="input_repeat_pwd">確認密碼</label>
<input id="input_repeat_pwd" type="password" name="user_repeat_pwd" placeholder="請再次輸入密碼" />
</div>
<div class="clothes">
<label for="input_email">註冊郵箱</label>
<input id="input_email" type="text" name="user_email" placeholder="請輸入郵箱地址" />
</div>
<div class="clothes">
<button class="register btn" type="submit">註冊</button>
<a class="btn" href="http://localhost:3000/login">
<button type="button">登陸</button>
</a>
</div>
</form>
</div>
</body>
</html>
public/login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>用戶登陸</title>
<link rel="stylesheet" type="text/css" href="css/index.css"/>
</head>
<body>
<div id="outer_box" class="login">
<h2>用戶登陸</h2>
<form action="http://localhost:3000/login" method="post">
<div class="clothes">
<label for="input_name">用 戶 名</label>
<input id="input_name" type="text" name="user_name" placeholder="請輸入用戶名" />
</div>
<div class="clothes">
<label for="input_pwd">密 碼</label>
<input id="input_pwd" type="password" name="user_pwd" placeholder="請輸入密碼" />
</div>
<div class="clothes">
<a class="btn" href="http://localhost:3000/register">
<button type="button">註冊</button>
</a>
<button class="login btn" type="submit">登陸</button>
</div>
</form>
</div>
</body>
</html>
public/css/index.css
body { width: 100%; height: 100%; color: #000; background: #b9c2a4; background-size: cover; /* 指定背景圖片大小 */
}
/*************************************************/ #outer_box { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); color: #1a45c3;
} #outer_box.login { color: #9e098b;
} #outer_box.register { color: #1a45c3;
} #outer_box>h2{ padding-bottom: 40px; margin-left: -50px;
} .clothes { position: relative; width: 260px; display: flex; justify-content: space-between; margin: 20px 0; font-size: 18px; line-height: 32px;
} .tips { position: absolute; top: 0; right: -100%; margin-left: -50%; margin-top: 2px; width: 252px; height: 32px; text-align: center; color: #f00;
} .clothes>label{ width: 80px; text-align: center;
} .clothes>input{ width: 170px; height: 32px;
} button { width: 100%; height: 100%; font-size: 16px; background-color: #c4ceda; cursor: pointer;
} .clothes .btn{ width: 64px; height: 32px; margin: 0 20px;
} .clothes button.register{ background-color: #1a45c3; color: #fff;
} .clothes button.login{ background-color: #9e098b; color: #fff;
} #outer_box>h2 { position: relative;
} #server_info { display: block; width: 139px; height: 20px; border-radius: 10px; position: absolute; top: 0; right: 0; color: red; font-size: 14px; text-align: center; line-height: 20px; background-color: #cecece;
}
views/register.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>用戶註冊</title>
<link rel="stylesheet" type="text/css" href="css/index.css"/>
</head>
<body>
<div id="outer_box" class="register">
<h2>用戶註冊</h2>
<form action="http://localhost:3000/register" method="post">
<div class="clothes">
<label for="input_name">用 戶 名</label>
<input id="input_name" type="text" name="user_name" placeholder="請輸入用戶名" />
<div class="tips"><%= errInfo.name %></div>
</div>
<div class="clothes">
<label for="input_pwd">密 碼</label>
<input id="input_pwd" type="password" name="user_pwd" placeholder="請輸入密碼" />
<div class="tips"><%= errInfo.password %></div>
</div>
<div class="clothes">
<label for="input_repeat_pwd">確認密碼</label>
<input id="input_repeat_pwd" type="password" name="user_repeat_pwd" placeholder="請再次輸入密碼" />
<div class="tips"><%= errInfo.repeatPassword %></div>
</div>
<div class="clothes">
<label for="input_email">註冊郵箱</label>
<input id="input_email" type="text" name="user_email" placeholder="請輸入郵箱地址" />
<div class="tips"><%= errInfo.email %></div>
</div>
<div class="clothes">
<button class="register btn" type="submit">註冊</button>
<a class="btn" href="http://localhost:3000/login">
<button type="button">登陸</button>
</a>
</div>
</form>
</div>
</body>
</html>
views/login.ejs
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>用戶登陸</title>
<link rel="stylesheet" type="text/css" href="css/index.css"/>
</head>
<body>
<div id="outer_box" class="login">
<h2> 用戶登陸 <div id="server_info"> <%= data.info %> </div>
</h2>
<form action="http://localhost:3000/login" method="post">
<div class="clothes">
<label for="input_name">用 戶 名</label>
<input id="input_name" type="text" name="user_name" placeholder="請輸入用戶名" />
</div>
<div class="clothes">
<label for="input_pwd">密 碼</label>
<input id="input_pwd" type="password" name="user_pwd" placeholder="請輸入密碼" />
</div>
<div class="clothes">
<a class="btn" href="http://localhost:3000/register">
<button type="button">註冊</button>
</a>
<button class="login btn" type="submit">登陸</button>
</div>
</form>
</div>
</body>
</html>
db/connectDB.js
const mongoose = require('mongoose'); module.exports = new Promise((resolve, reject)=>{ mongoose.connect('mongodb://localhost:27017/user_database', {useNewUrlParser:true}) mongoose.connection.once('open', err=>{ if(err){ console.log(err); reject(err); }else{ resolve('數據庫已鏈接'); }; }); });
models/userModel.js
const mongoose = require('mongoose'); const Schema = mongoose.Schema; const fieldSchema = new Schema({ "userName": { "type": String, "unique": true, "required": true }, "userPassword": { "type": String, "required": true }, "userEmail": { "type": String, "unique": true, "required": true }, "createTime": { "type": Date, "default": Date.now() } }); module.exports = mongoose.model("user_info", fieldSchema);
routers/get/index_router.js
const express = require('express'); const {resolve} = require('path'); const indexRouter = new express.Router(); /************************ get ***********************/ indexRouter.get('/', (request, response)=>{ response.sendFile(resolve(__dirname, '../../public/login.html')); }); indexRouter.get('/login', (request, response)=>{ response.sendFile(resolve(__dirname, '../../public/login.html')); }); indexRouter.get('/register', (request, response)=>{ response.sendFile(resolve(__dirname, '../../public/register.html')); }); module.exports = indexRouter;
routers/post/form_router.js
const express = require('express'); const sha1 = require('sha1'); const promiseConnect = require('../../db/connectDB.js'); const userInfoModel = require('../../models/userModel.js'); const formRouter = new express.Router(); /************************ post ***********************/ let logged = false ; promiseConnect.then(async result=>{ console.log(result); formRouter.post('/register', async (request, response)=>{ const { user_name:uName, user_pwd:uPwd, user_repeat_pwd:urePwd, user_email:uEmail, } = request.body; /**** 解構賦值 ****/ userInfo = { "userName": uName, "userPassword": uPwd, "userEmail": uEmail }; let errInfo = {}; if(urePwd !== uPwd){ errInfo.repeatPassword = '密碼兩次輸入不一致'; }; if(!(/^[a-zA-Z][a-zA-Z0-9_]{5,20}$/.test(uName))){ errInfo.name = '用戶名不合法'; }; if(!(/^[a-zA-Z0-9_]{6,20}$/.test(uPwd))){ errInfo.password = '密碼不合法'; }; if(!(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/.test(uEmail))){ errInfo.email = '郵箱不合法'; }; const fond = await userInfoModel.findOne({"userName": uName}); if(fond){ errInfo.name = '用戶名已被註冊'; }; const badEmail = await userInfoModel.findOne({"userEmail": uEmail}); if(badEmail){ errInfo.email = '郵箱已被註冊'; }; let data = {errInfo}; if(errInfo.repeatPassword || errInfo.name || errInfo.password || errInfo.email){ response.render('register.ejs', data); return; }else{ userInfo.userPassword = sha1(userInfo.userPassword); await userInfoModel.create(userInfo); data.info = "註冊成功"; response.render('login.ejs', {data}); }; }); formRouter.post('/login',async (request, response)=>{ logged = false; let uName = request.body['user_name']; let uPwd = request.body['user_pwd']; userInfo = { "userName": uName, "userPassword": uPwd }; if(!(/^[a-zA-Z][a-zA-Z0-9_]{5,20}$/.test(uName))){ logged = false; // 用戶名不存在
}else if(!(/^[a-zA-Z0-9_]{6,20}$/.test(uPwd))){ logged = false; // 密碼錯誤
}; const findName = await userInfoModel.findOne({"userName": uName}); const findPwd = await userInfoModel.findOne({"userPassword": sha1(uPwd)}); if(findName && findPwd){ logged = true; }; let data = {}; logged?(data.info='登陸成功'):(data.info='用戶名或密碼錯誤'); response.render('login.ejs', {data}); }); }).catch(err=>console.log(err)); module.exports = formRouter;
index.js
const express = require('express'); const app = express(); const indexRouter = require('./routers/get/index_router.js'); const formRouter = require('./routers/post/form_router.js'); app.set('views', 'views'); // 1. 配置模板路徑 app.set('view engine', 'ejs'); // 2. 配置模板引擎 /*********************** 中間件 **********************/
// 暴露路由 login.html register.html app.use(express.static('public')); // 默認調用 next(); // 將 用戶輸入的數據 掛載到 請求體 request.body 上 app.use(express.urlencoded({extended: true})); // 默認調用 next(); app.use(indexRouter); app.use(formRouter); /**************** 端口號 3000, 啓動服務器 ***************/ app.listen(3000, err=>console.log(err?err:'\n\n服務器已啓動: http://localhost:3000\nHunting Happy!'));