[英]Can't get a specific property of js object
我正在使用 ejs、mongodb 和快递。 在 ejs 文件中,我将编辑按钮的值设置为传递到 ejs 文件中的 js object,以便在编辑按钮向路由发出发布请求后,我可以在快递中查询所需的数据。 EJS编辑按钮代码:
<% listOfRecords.forEach((singleRecord)=>{ %>
<div class="card card-body">
<form method="post">
<button formaction="/edit" class="btn btn-success btn-sm" name="editBtn" value="<%=singleRecord%>">Edit</button>
</form>
</div>
<% }); %>
但是,我可以通过以下代码在控制台中记录 js object:
app.post('/edit', (req, res)=>{
console.log(req.body.editBtn);
});
上述代码的output为:
{
_id: 60605148a1fba61fd8f2446f,
title: 'asdf',
author: 'sadf',
class_section: 'asfd',
dateIssued: 2021-03-01T00:00:00.000Z,
__v: 0
}
但是当我尝试这样做时: console.log(req.body.editBtn.title);
它显示错误, undefined
我在这做错了什么?
我认为我们没有足够的信息。 从我的角度来看,代码看起来不错。 它应该工作。
您可以尝试做的是通过执行console.log(req.body.editBtn['title']);
来获取属性。 而不是console.log(req.body.editBtn.title);
.
您也可以尝试解构标题: const { title } = req.body.editBtn
。
虽然这些理论上应该不起作用? 也许您的代码中的其他内容是错误的?
编辑:
如果req.body.editBtn
是一个字符串,那么试试JSON.parse(req.body.editBtn);
然后得到你想要的属性。
真正的问题是req.body.editBtn
是字符串格式。 因此,要完成这项工作,EJS 文件中的更改将是:
<button formaction="/edit" class="btn btn-success btn-sm" name="editBtn" value="<%=JSON.stringify(singleRecord)%>">Edit</button>
这应将 js object 正确转换为字符串,然后在 express 文件中,更改为:
let editBtn = req.body.editBtn;
let info = JSON.parse(editBtn);
现在我可以访问 object 的任何属性,因为它已正确转换为字符串和从字符串转换。
您应该从JSON.parse方法的 output 获取属性,而不是仍然是字符串的 req.body.editBtn。
app.post('/edit', (req, res)=>{
const data = JSON.parse(req.body.editBtn);
// console.log(req.body.editBtn);
console.log(data.title);
console.log(data.author);
// ....
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.