簡體   English   中英

無法獲取 js object 的特定屬性

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM