我很高兴发布我的第一个Stack Overflow查询。 :d
我最近开始了一个Node.js课程,我只是想指出我还没有做任何硬核的东西。
我有一个运行nodemon的本地节点服务器。我开始使用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>
<% } %>
我希望代码呈现页面,但收到错误:
“我的vscode终端中的”SyntaxError:在C:\ Users \ Ruan Buitendag \ Documents \ NodeJS \ Practice Server \ views \ shop.ejs中编译ejs时出现意外的令牌“和内容安全策略:页面的设置阻止了资源的加载在我的浏览器控制台中的内联(“default-src”)“。
编辑:PS。我尝试在firefox开发者版,普通的firefox和谷歌浏览器中运行该页面。
我认为问题出在你的循环中。以这种方式使用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 (var product of prods) { %>
...