[英]How do I pass objects from NodeJS to javascript files with EJS
Down below you can see I have a nodeJS server which passes down a data object to the index page.在下面你可以看到我有一个 nodeJS 服务器,它将数据 object 传递到索引页面。 Inside of my index.ejs file I can receive this data using <%= data %> however this only gives [object Object].
在我的 index.ejs 文件中,我可以使用 <%= data %> 接收这些数据,但这只会给出 [object Object]。 However, what I want is to receive this data inside my javascript file as an acutal object so I can use the data to do stuff.
但是,我想要的是在我的 javascript 文件中接收这些数据作为实际的 object,这样我就可以使用这些数据来做事。 How can I acheive this?
我怎样才能做到这一点?
NodeJS:节点JS:
router.get("/", getData, (req, res) => {
res.render("index", { data: data }); // Where 'data' is a large object with lots of information
});
index.ejs:索引.ejs:
<html>
<head>
...
<script defer src="myScript.js"></script> <!-- I want to pass the data object to this file -->
</head>
<body>
<%= data %> <!-- This works, but is not what I want -->
</body>
</html>
myScript.js: myScript.js:
const data = <%= data %> // this doesnt work, but is what I need
JSON is a data exchange language based on literal syntax for JavaScript. JSON是一种基于 JavaScript 的字面语法的数据交换语言。 So long as your data consists entirely of data types supported by JSON (such as plain objects and numbers) you can use it to generate a string that you can insert into a data attribute and parse with `JSON.parse .
只要您的数据完全由 JSON 支持的数据类型(例如普通对象和数字)组成,您就可以使用它来生成一个字符串,您可以将其插入数据属性并使用`JSON.parse解析。
<script data-data="<%= JSON.stringify(data) %>">
const data = JSON.parse(document.currentScript.dataset.data);
</script>
If your object includes features not supported by JSON, such as functions, symbols, etc. then you'll need to special case how they are transferred across.如果您的 object 包含 JSON 不支持的功能,例如函数、符号等,那么您需要对它们的传输方式进行特殊处理。
An earlier version of this answer used a similar technique that treated the JSON as JavaScript source code.此答案的早期版本使用了类似的技术,将 JSON 视为 JavaScript 源代码。 This more-or-less works, but is vulnerable to XSS since if the data contains a string
"</script>"
that will terminate the script element in the middle of the string literal.这或多或少有效,但容易受到 XSS 的攻击,因为如果数据包含一个字符串
"</script>"
,它将终止字符串中间的脚本元素。 There is a potential that further data in the string could pose a more serious XSS threat.字符串中的更多数据有可能构成更严重的 XSS 威胁。
You could use that technique, but you would need to mitigate that attack by escaping /
characters.您可以使用该技术,但您需要通过 escaping
/
字符来减轻该攻击。
Try like this:试试这样:
<html>
<head>
...
<script>var data = <%= JSON.stringify(data) %>;</script>
<script defer src="myScript.js"></script> <!-- I want to pass the data object to this file -->
</head>
<body>
</body>
</html>
UPDATE更新
Security concern: If your object contain user supplied datas, your page will possibly become subject to injection安全问题:如果您的 object 包含用户提供的数据,您的页面可能会受到注入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.