• 创建 index.ejs
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <h2>
            <%- data %>
        </h2>
        <h2>
            <%- name %>
        </h2>
        <h2>
            <% user.forEach((item)=>{ %>
            姓名是: <%- item.name %>
            性别是: <%- item.sex %>
            年龄是: <%- item.age %>
            <br>
            <% }) %>
        </h2>
    </body>
    </html>
    
  • 搭建node.js服务器
    //引入express
    const express = require("express");
    //引入path
    const path = require("path");
    //创建一个express的application对象
    const app = express();
    //首先引入ejs
    const ejs = require("ejs");
    //通知express使用ejs模板引擎
    app.set("view engine", "ejs");
    app.set("views", "views");
    app.get("/", (req, res) => {
        //获取模板的路径
        const filePath = path.resolve(__dirname, "index.ejs");
        const data = "hello jingjing";
        res.render(filePath, {
            data: data,
            name: "laowang",
            user: [{
                name: "laowang",
                age: 18,
                sex: "nan"
            }, {
                name: "xiaowang",
                age: 19,
                sex: "nv"
            }, {
                name: "zhongwang",
                age: 28,
                sex: "nan"
            }, {
                name: "dawang",
                age: 38,
                sex: "nv"
            }]
        })
    })
    //监听端口号和服务器状态
    let port = "3002";
    app.listen(port, err => {
        if (err) {
            console.log(err);
            return;
        }
        console.log("服务器启动,请访问" + ` http://127.0.0.1:${port}`);
    })
    
posted on 2021-06-09 20:22  文种玉  阅读(260)  评论(0编辑  收藏  举报