zoukankan      html  css  js  c++  java
  • Node.js_express_服务器渲染页面 ejs

    服务器渲染页面 ejs

    高效的 js 模版引擎

    将数据提前渲染到页面上, 再将渲染好的页面返回响应给浏览器

     

    提高首页加载速度

    SEO 提前处理,提高加载速度

    • 下载 ejs 包

    npm install ejs

    无需引用,但是要配置模板资源目录

    // app.set('views', '模板资源目录');

    app.set('views', 'views');    // 通常文件夹 也叫 views

    • 基本使用

    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">&nbsp;&nbsp;</label>
                          <input id="input_name" type="text" name="user_name" placeholder="请输入用户名" />
                      </div>
              
                      <div class="clothes">
                          <label for="input_pwd">&nbsp;&nbsp;&nbsp;</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">&nbsp;&nbsp;</label>
                          <input id="input_name" type="text" name="user_name" placeholder="请输入用户名" />
                      </div>
                      
                      <div class="clothes">
                          <label for="input_pwd">&nbsp;&nbsp;&nbsp;</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">&nbsp;&nbsp;</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">&nbsp;&nbsp;&nbsp;</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">&nbsp;&nbsp;</label>
                          <input id="input_name" type="text" name="user_name" placeholder="请输入用户名" />
                      </div>
                      
                      <div class="clothes">
                          <label for="input_pwd">&nbsp;&nbsp;&nbsp;</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:'
      
      服务器已启动: http://localhost:3000
      Hunting Happy!'));

     

    --------小尾巴 ________一个人欣赏-最后一朵颜色的消逝-忠诚于我的是·一颗叫做野的心.决不受人奴役.怒火中生的那一刻·终将结束...
  • 相关阅读:
    215. Kth Largest Element in an Array(partition逆序排序,index+1 == k)
    220. Contains Duplicate III(核心:set数组有序/桶排序)
    leetcode 772 基本计算器III(包含+-*/ 以及括号) 核心在于递归
    MTK8312 android 4.4 显示虚拟按键区源码修改
    高通android9.0 camera API1底层调用为HAL3而非HAL1
    使用yanzhenjie的Zbar Github项目时4.2版本上找不到so库的问题
    android studio CMake NDK:配置笔记
    android设置系统默认开机时间
    android开发里跳过的坑——GridView使用Glide加载图片不显示
    android系统编译打开系统蓝牙
  • 原文地址:https://www.cnblogs.com/tianxiaxuange/p/10161688.html
Copyright © 2011-2022 走看看