我使用 Handlebars 作为我的模板引擎并且是 handlebars 的新手。我传递了来自 API(edamam 食谱搜索 api)的数据。当尝试使用表单中的隐藏值发回附加到每个食谱卡的配料数组时,我在服务器端收到错误消息。控制台显示
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object] [object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
尝试在服务器端注销时。不确定发生了什么。代码如下:
<div class="container">
<header class="jumbotron">
<div class=container></div>
<h1>{{currentUser.username}}</h1>
<h1>Press save to add the recipes to your dashboard</h1>
<p>
<a class="btn btn-primary btn-large" href="/{{currentUser.username}}/recipes/dashboard">Go To Your Dashboard</a>
</p>
</header>
<div class="row text-center" style="display:flex; flex-wrap:wrap">
{{#each data}}
<div class="col-md-3 col-sm-6">
<div class="thumbnail">
<img src="{{recipe.image}}" alt="Recipe Pic">
<div class="caption">
<h4>
{{recipe.label}}
</h4>
<h5>
Ingredients
</h5>
{{!-- recipe.ingredients is an array of ingredient objects with text as a key --}}
{{#each recipe.ingredients}}
<p>{{text}}</p>
{{/each}}
</div>
<p>
<form id="buttonDesign" action="/recipes/dashboard" method="POST">
<input type="hidden" name="recName" value="{{this.recipe.label}}"/>
<input type="hidden" name="recImage" value="{{this.recipe.image}}"/>
<input type="hidden" name="recUrl" value="{{this.recipe.url}}"/>
<input type="hidden" name="recIngredients" value "{{this.recipe.ingredients}}"/>
<button class="btn btn-primary">Save</button>
</form>
</p>
</div>
</div>
{{/each}}
</div>
</div>
</div>
如上所述,当我在服务器端注销 req.body.recIngredients 时,出现 [object, Object]
错误。
最佳答案
您使用模板引擎传递的数据是直接对象,例如{{this.recipe.ingredients}} 因此,当此对象“this.recipe.ingredients”转换为字符串时,它会转换为“[[Object object]]”,这是 Object#toString() 方法提供的默认字符串响应.您需要做的是首先将您的对象转换为字符串,然后将其分配给 html 元素的属性值。
对于转换,您可以使用“JSON.stringify(this.recipe.ingredients)”,它将您的整个对象转换为 JSON 格式的字符串。
我不知道“Handlebars 模板引擎”,但这应该有效:
{{JSON.stringify(this.recipe.ingredients)}}。
是的,你忘了放“=” <input type="hidden" name="recIngredients" value "{{this.recipe.ingredients}}"/>
将值属性与其实际值“{{this.recipe.ingredients}}”相关联。
关于javascript - 在服务器端将隐藏值数据作为数组发送时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55391327/