【问题标题】:Can't get a specific property of js object无法获取 js 对象的特定属性
【发布时间】:2021-03-28 10:09:32
【问题描述】:

我正在使用 ejs、mongodb 和 express。在 ejs 文件中,我已将 Edit 按钮的值设置为传递到 ejs 文件中的 js 对象,以便在 Edit 按钮向路由发出 post 请求后,我可以在 express 中查询所需的数据。 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 对象:

app.post('/edit', (req, res)=>{
    console.log(req.body.editBtn);
});

以上代码的输出为:

{
  _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(typeof req.body.editBtn)
  • @MikeM 哦,它显示的是字符串而不是对象
  • @MikeM 那么现在完成相同任务的解决方法是什么?
  • 好吧,如果你敢的话,你可以使用正则表达式来获取标题。
  • @MikeM 实际上我想要它的所有属性,那么我该怎么做呢?

标签: javascript mongodb express ejs


【解决方案1】:

我认为我们没有足够的信息。从我的角度来看,代码看起来不错。它应该可以工作。

您可以尝试通过 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 是字符串格式,所以editBtn.title 的方法不起作用,当我尝试这样做时:const info = JSON.parse(req.body.editBtn); 显示出一些更奇怪的错误。请问您知道任何解决方法吗?
【解决方案2】:

真正的问题是req.body.editBtn 是字符串格式。因此,要完成这项工作,EJS 文件中的更改将是:

<button formaction="/edit" class="btn btn-success btn-sm" name="editBtn" value="<%=JSON.stringify(singleRecord)%>">Edit</button>

这会将js对象正确转换为字符串,然后在express文件中,更改为:

let editBtn = req.body.editBtn;
let info = JSON.parse(editBtn);

现在我可以访问对象的任何属性,因为它已正确转换为字符串。

【讨论】:

    【解决方案3】:

    您应该从 JSON.parse 方法的输出中获取属性,而不是仍然是字符串的 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);
        // ....
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-08
      • 2016-06-30
      • 1970-01-01
      相关资源
      最近更新 更多