EJS 模板引擎

https://www.npmjs.com/package/ejs

安装:npm install ejs --save

app.js

const http = require('http');
const url = require('url')
const ejs = require('ejs')
const staticWeb = require('./web')

http.createServer(function (request, response) {
    //创建静态Web服务
    staticWeb(request,response,'./static')
    //路由
    let pathname = url.parse(request.url).pathname
    if (pathname == '/') {
        response.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
        response.end("<h3>执行首页逻辑</h3>");
    }
    else if(pathname=='/login'){
        // response.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
        // response.end("<h3>执行登录逻辑</h3>");
        let list = [
            {
                name:"张三",
                age:11
            },
            {
                name:"李四",
                age:23
            },
            {
                name:"jack",
                age:45
            }
        ]
        ejs.renderFile('./views/login.ejs',{
           list:list
        }, (err, data) => {
            response.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' })
            response.end(data)
        })
    }
    else if(pathname=='/register'){
        //response.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
        //response.end("<h3>执行注册逻辑</h3>");
        let msg = "这是来自服务器的数据"
        ejs.renderFile('./views/register.ejs', {
            msg: msg
        }, (err, data) => {
            response.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
            response.end(data);
        })
    }
    else if(pathname=='/loginOut'){
        response.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
        response.end("<h3>执行退出登录逻辑</h3>");
    }
    else{
        response.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' });
        response.end("<h3>404 Not Found</h3>");
    }
}).listen(8081);

console.log('Server running at http://127.0.0.1:8081/');

后端路由执行登录逻辑,渲染 login.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h3>登录.ejs</h3>
    <ul>
        <%for(var i=0;i<list.length;i++){%>
        <li><%=list[i].name%></li>
        <li><%=list[i].age%></li>
        <%}%>
    </ul>
</body>
</html>

后端路由执行注册逻辑,渲染 register.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h3>注册.ejs</h3>
    <h3><%=msg%></h3>
</body>

</html>

 

posted @ 2021-02-02 00:16  shanlu  阅读(68)  评论(0编辑  收藏  举报