others - javascript - Handlebars: Access has been denied to resolve the property "from" because it is not an "own property" of its parent

我使用一個Nodejs後端,伺服器端使用handlebars呈現,當我嘗試使用#each循環遍歷對象數組時,出現錯誤"Handlebars:Access has been denied to resolve the property "from" because it is not an "own property" of its parent " appears.



Confession.find()


 .sort({date: -1})


 .then(function(doc){


 for(var i=0; i < doc.length; i++){


 //Check whether sender is anonymous


 if (doc[i].from ==="" || doc[i].from == null){


 doc[i].from ="Anonymous";


 }



 //Add an extra JSON Field for formatted date


 doc[i].formattedDate = formatTime(doc[i].date);


 }


 res.render('index', {title: 'Confession Box', success:req.session.success, errors: req.session.errors, confession: doc});


 req.session.errors = null;


 req.session.success = null;


 });

這是我試圖循環的.hbs文件的一部分:


 {{#each confession}}


 <div class="uk-card uk-card-default uk-card-body uk-margin uk-align-center uk-width-1-2@m" >


 <div class="uk-text-bold">Message: </div>


 <div>{{this.content}}</div>


 <div>From: {{this.from}}</div>


 <div>Posted: {{this.formattedDate}}</div>


 </div>


 {{/each}}

时间: 作者:

通過為handlebars安裝dev依賴項來解決這個問題

npm i -D handlebars@4.5.0

作者:

以下是我如何解決這個問題:


// * USERS PAGE


// @description users route


// @returns ../views/users.hbs


router.get('/users', async (req, res) => {


 // get all items from db collection


 const collection = 'User'


 await dbFindAllDocs(collection) // <=> wrapper for Model.find() ...


 .then(documents => {


 // create context Object with 'usersDocuments' key


 const context = {


 usersDocuments: documents.map(document => {


 return {


 name: document.name,


 location: document.location


 }


 })


 }


 // rendering usersDocuments from context Object


 res.render('users', {


 usersDocuments: context.usersDocuments


 })


 })


 .catch(error => res.status(500).send(error))


})



users.hbs文件


<ul>


{{#each usersDocuments}}


<li>name: {{this.name}} location: {{this.location}}</li>


{{/each}} 


</ul>



創建一個context的新對象,然後將它傳遞給render函數將修復這個問題。

作者:

在最近發布的Handlebars中有一個重大更改導致這個錯誤。

https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access


Confession.find()


 .sort({date: -1})


 .then(function(doc){


 for(var i=0; i < doc.length; i++){


 //Check whether sender is anonymous


 if (doc[i].from ==="" || doc[i].from == null){


 doc[i].from ="Anonymous";


 }



 //Add an extra JSON Field for formatted date


 doc[i].formattedDate = formatTime(doc[i].date);


 }


 res.render('index', {title: 'Confession Box', success:req.session.success, errors: req.session.errors, confession: doc}, {



 // Options to allow access to the properties and methods which as causing the error.



 allowProtoMethodsByDefault: true,


 allowProtoPropertiesByDefault: true



 });



 req.session.errors = null;


 req.session.success = null;


 });



作者:
...