javascript - 找不到“<%”的匹配结束标记
问题描述
我正在尝试使用 ejs 访问从服务器传递到客户端的变量
我的服务器文件:
router.get('/', function (req, res, next) {
res.render('chat', {user: req.user, message: null});
});
我的客户文件:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" const="text/html;charset=UTF-8"/>
<link href="http://fonts.googleapis.com/css?family=Comfortaa" rel="stylesheet" type="text/css">
<link rel="stylesheet" type="text/css" href="style.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.4/socket.io.js"></script>
<title>Simple Chat App</title>
</head>
<body>
<header>
<h1>Super Chat</h1>
</header>
<section>
<div id="change_username">
<input id="username" type="text"/>
<button id="send_username" type="button">Change username</button>
</div>
</section>
<section id="chatroom">
<section id="feedback"></section>
</section>
<section id="input_zone">
<input id="message" class="vertical-align" type="text"/>
<button id="send_message" class="vertical-align" type="button">Send</button>
</section>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
<% var user = <% user %> %>
console.log(user);
</script>
<script src="chat.js"></script>
</body>
</html>
我收到一个错误:
Could not find matching close tag for "<%".
我该如何解决?
解决方案
<% var user = <% user %> %>
你不能嵌套<% %>
块。你要么在 EJS 模式之内,要么在它之外。您无法进入 Extra Deep EJS 模式。
此外,您也不能只将变量输出到客户端 JS 中。您需要从变量生成 JavaScript 源代码。JSON.stringify
是从对象、数组和字符串生成对象、数组和字符串字面量的好方法。
<script>
const user = <%- JSON.stringify(user); %>
console.log(user);
</script>
请注意,使用 of<%-
输出而不转义 HTML。
推荐阅读
- mongodb - 更新 mongodb 中的嵌套数组元素
- python - 如何在python中显示当前月份的前6个月数据
- javascript - D3 中的 parseTime 和函数有错误
- android - Lottie 动画根本没有显示
- mysql - 实体框架选择单个子类别
- python - Python - 获取适用于 Web 应用程序的 Python3.8 新功能 PYTHONPYCACHEPREFIX
- mongodb - 从子对象 Mongodb 中仅检索所需的元素
- c - 我有一个链表,我想删除重复值
- c++ - 交叉依赖类的问题
- python - 为什么当我设置谷歌浏览器配置文件时 selenium 崩溃?