我正在尝试将JSON数据从后端传递到ejs前端,这是我的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Advanced React Application Example</title>
<script type="text/javascript">
window.initialData = <%- JSON.stringify(initialData) -%>
</script>
</head>
<body>
<div id="root">
<%- initialMarkup -%>
<%- JSON.stringify(initialData) -%>
</div>
</body>
<!-- place the bundle file in th public dir -->
<script src="/bundle.js" charset="UTF-8"></script>
</html>
我遇到了语法错误,它表示找不到initialData,但是在正文部分,数据呈现没有任何问题。谁能知道这是什么错误?
window.initialData = <% - JSON.stringify(initialData) %>
以下是我来自服务器端代码的数据:
app.get("/", async (req, res) => {
const initialContent = await serverRender();
res.render("index", {
initialData: initialContent.initialData,
initialMarkup: initialContent.initialMarkup,
});
});
initialData是json格式。下面是示例数据:
{articles: [
{
id: "95c12a8f6c88953ca8f8a39da25546e6",
title: "Introducing React's Error Code System",
date: "Mon Jul 11 2016 00:00:00 GMT+0000 (UTC)",
authorId: "2c6aa2cfe3449467d329fa17d6ea230f",
body:
"Building"
}],
authors: [
{
id: "d85577ea34ae50f2dac5347b5219aa23",
firstName: "Andrew",
lastName: "Clark",
website: "https://twitter.com/acdlite"
}]
}