使用模板引擎和服务端渲染。
通常,用户触碰HTML或JS会导致安全漏洞。因此我们应该尽可能避免用户修改这些代码。而模板引擎和服务端渲染可以有效地将视图文件转换为HTML,从而避免用户触碰HTML或JS代码。下面是一个示例:
在Node.js上使用Express框架生成默认项目结构。
安装必要的依赖:
npm install ejs
npm install express
npm install express-handlebars
const express = require('express');
const handlebars = require('express-handlebars');
const ejs = require('ejs');
const app = express();
const port = 3000;
app.engine('.hbs', handlebars());
app.set('view engine', '.hbs');
app.get('/', function(req, res) {
res.render('payment', {
title: 'Payment Page',
amount: 10
});
});
app.get('/ejs', function(req, res) {
res.render('payment.ejs', {
title: 'Payment Page',
amount: 20
});
});
app.listen(port, function() {
console.log(`Server started on port ${port}`);
});
{{ title }}
{{ title }}
Amount: {{ amount }}
<%= title %>
<%= title %>
Amount: <%= amount %>
最后,在浏览器中访问 http://localhost:3000 和 http://localhost:300