在控制台上的 EJS 变量中打印 json 数组时出错

Getting error when printing json array in EJS variable on console

伙计们,我正在使用 expressjs、ejs 开发在线购物网站。

场景 为了显示产品 {name, description, imageUrl} 我在网页上借助 ejs control-flow 进行迭代。

我正在发送一个数组,其中包含 JSON 格式的每个产品的所有详细信息。 (来自服务器) 在客户端,当我尝试访问这个 json 数组时出现以下错误。

(index):266 Uncaught SyntaxError: Invalid or unexpected token

当我在 google chrome 中打开源选项卡时,向我展示了这个

在行号 266。我相信它通过将数组用双引号引起来将其作为字符串。?

谁能告诉我这段代码出了什么问题?

顺便说一下,我是如何尝试在 chrome 控制台

上打印数组的
  <script>
    const data = JSON.parse("<%- products %>");
    console.log(data);
  </script>

其中产品是 json 数组

发送JSON数组的后端home路由如下

router.get("/", async (req, res) => {
  let catalogInformation = {};
  //getAllProducts returns array of json from the database
  const products = await getAllProducts();
  catalogInformation.products = products;
  userData = {
    email: null,
    username: null,
  };
  catalogInformation.userData = userData;
  if (req.session.userInformation != null || req.session.userInformation != undefined) {
    catalogInformation.userData = req.session.userInformation;
  } else {
    catalogInformation.userData = {
      email: null,
      username: null,
    };
  }
  // res.render("catalog", userData);
  res.render("catalog", catalogInformation);
  return;
});

getAllProducts()方法

const getAllProducts = async () => {
  const Product = mongoose.model("product", productSchema);
  const allProducts = await Product.find();
  return allProducts;
};

您不需要使用 JSON.parse。直接输出JSON即可:

var data = <%- products %>;

我不建议进行 AJAX 调用,因为您将处理 2 个请求而不是 1 个。