我很高兴发布我的第一个 Stack Overflow 查询。 :D
我最近开始了一门 Node.js 类(class),我只想指出我还没有做任何硬核的事情。
我有一个使用 nodemon 运行的本地 Node 服务器。我开始使用 ejs 并发现 forEach 循环由于某种原因正在融化我的网页。
我尝试进行研究并筛选我的代码,逐个删除问题之前不存在的某些部分,直到问题消失,并发现当我从 ejs 文件中的代码中取出 forEach 循环时,问题就消失了。
//this is my .js file located in my ./routes folder
const express = require('express');
const router = express.Router();
const admin_data = require('./admin');
router.get('/', (req, res, next) => {
const products = admin_data.products;
res.render('shop', {
page_title: 'Shop',
prods: products
});
});
//nothing too hectic.
//this is my ejs file located in my ./views folder.
<% if (prods.length > 0) { %>
<div class="grid">
<% forEach (var products in prods) { %> //if i remove this and it's closing '}' it works fine.
<article class="card product-item">
<header class="card__header">
<h1 class="product__title">product</h1>
</header>
<div class="card__image">
<img src="" alt="A Book">
</div>
<div class="card__content">
<h2 class="product__price">$19.99</h2>
<p class="product__description">A very interesting book about so many even more interesting things!
</p>
</div>
<div class="card__actions">
<button class="btn">Add to Cart</button>
</div>
</article>
<% } %>
</div>
<% } %>
我希望代码能够呈现页面,但却收到错误:
"SyntaxError: Unexpected token { in C:\Users\Ruan Buitendag\Documents\NodeJS\Practice Server\views\shop.ejs while compiling ejs" in my vscode terminal and "Content Security Policy: The page’s settings blocked the loading of a resource at inline (“default-src”)" in my browser console.
编辑:PS。我尝试在 Firefox 开发者版、普通 Firefox 和 google chrome 中运行该页面。
最佳答案
我认为问题出在你的循环中。以这种方式使用 forEach
:
<% prods.forEach(function(product) { %>
<article class="card product-item">
<header class="card__header">
<h1 class="product__title">product</h1>
</header>
<div class="card__image">
<img src="" alt="A Book">
</div>
<div class="card__content">
<h2 class="product__price">$19.99</h2>
<p class="product__description">A very interesting book about so many even more interesting things!</p>
</div>
<div class="card__actions">
<button class="btn">Add to Cart</button>
</div>
</article>
<% }) %>
或者,您可以使用 for...of 循环,如下所示:
<% for (var product of prods) { %>
...
关于node.js - Node ejs forEach 导致 'Content Security Policy' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54704192/