EJS模板引擎助力SSR项目

依赖

                                npm i ejs
                            

app中配置

                                const app = express();

app.set('view engine', 'ejs');// 设置视图引擎,在根目录创建views目录存放ejs模板
app.set('views', path.join(__dirname, 'views')); // 默认查找 views 文件夹
app.use(express.static(path.join(__dirname, 'public')));//静态文件夹,可以存放模板页面显示要用的图片,css
app.use('/', require('./routes'));//路由
                            

routes/index

                                const  router = require('express').Router();

router.use('/',require('./webAPI'))

module.exports = router;
                            

routes/webAPI 路由配置

                                const router = require('express').Router();
const api = require('../controller/web');

router.get('/', api.homeAPI);
router.get('/content', api.contentAPI);
router.get('/pay', api.payAPI);
router.get('/order/id', api.orderIdAPI);
router.get('/order/name', api.orderNameAPI);
router.get('/404', api.errorAPI);

module.exports = router;
                            

controller/web 路由逻辑

                                exports.homeAPI = async (req, res, next) => {
        // 获取参数
        const { title, name, page = 1 } = req.query;
        // 渲染页面
        res.render('index', {
         // 存放返回前端的数据,这里可以接收前端参数,直接查询数据库
        });
                            

views/index.ejs

                                <!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <meta name="keywords" content="史努比虚拟商城,壁纸,漫画,小说,网盘链接,文件,音乐,动漫,电影,软件,账号,交易中心-<%= keywords %>">
    <meta name="description" content="史努比虚拟商城,壁纸,漫画,小说,网盘链接,文件,音乐,动漫,电影,软件,账号,交易中心-<%= keywords %>">
    <!-- 提交百度,必应,谷歌等引擎的凭据 -->
    <meta name="baidu-site-verification" content="codeva-blD2OyjxwZ" />
    <meta name="msvalidate.01" content="597C554BBBA9194BCD4EA2878D8A0DA3" />
    <meta name="google-site-verification" content="BJz3eFVyD-HxI956FBzjLGi5or8arruOhrFE-7CarDg" />
    <!-- 静态资源 -->
    <link rel="icon" type="image/png" href="/favicon.png"/>
    <link rel="stylesheet" href="/css/index.css">
    <title>史努比虚拟商城</title>
</head>
<body>
页面结构
<script>
js逻辑
</script>
</body>
</html>
                            

模板语法

                                <%= keywords %> // 获取接口返回的数据直接展示

// 循环列表展示
<% weblogs.forEach(function (item){ %>
// 列表嵌套条件渲染
<% if (item.type === 'title') { %>

<% } else if (item.type === 'paragraph') { %>

<% } %>

<% }) %>

// 内容如果是富文本,可用此转义
<p><%- aboutContent %></p>
                            

结束部署

1.只用部署node就可以即给管理端提供接口,也可以服务端渲染用户界面。

2.服务端渲染,有利于SEO

3.开发简单,可以通过路由直接调用数据库,避免看到接口,更加安全

4.组装数据都在服务端,对服务器压力不小

上一篇

将文字转成图片上传

下一篇

短链业务,内容是http协议在微信等平台无法打开时候的解决办法

史努比博客