我將這個網站作為一個專案,它是 AirBnB 的“沃爾瑪”版本。
這是按鈕應該為背景關系執行的操作:
用戶將單擊串列上的“進行預訂”按鈕。他們將選擇開始和結束日期,然后提交。這將向服務器發送 HTTP 請求。
但是,我遇到了回傳的錯誤:
TypeError:無法讀取 /vagrant/LightBnB/LightBnB_WEB_APP/server/apiRoutes.js:44:7 <--
第 44:7 行是下面的 API 路由:
這導致了錯誤:
.then((reservation) => {
res.send(reservation);
這是導致問題的 API ROUTE Logic:
router.post('/reservations', (req, res) => {
const userId = req.session.userId;
database
.addReservation({ ...req.body, guest_id: userId })
.then((reservation) => {
res.send(reservation);
})
.catch((e) => {
console.error(e);
res.send(e);
});
});
該路線正在呼叫函式 addReservation(),如下所示:
/**
* Add a reservation to the database
* @param {{}} reservation An object containing all of the reservation details.
* @return {Promise<{}>} A promise to the reservation.
*/
const addReservation = function (reservation) {
const queryString = `
INSERT INTO reservations(
start_date,
end_date,
property_id,
guest_id
)
VALUES ($1, $2, $3, $4)
RETURNING *
`;
const values = [
reservation.start_date,
reservation.end_date,
reservation.property_id,
reservation.guest_id,
];
pool
.query(queryString, values)
.then((res) => {
res.rows;
})
.catch((e) => console.log(e.message));
};
exports.addReservation = addReservation;
如果您需要更多資訊,請告訴我。
uj5u.com熱心網友回復:
TypeError:無法讀取未定義的屬性“then”
addReservation()沒有回傳值,因此它回傳undefined. 因此,當您嘗試這樣做時addReservation(...).then(...),您最終會嘗試訪問導致您得到錯誤的結果.then()。undefined
在 內部addReservation(),您需要更改:
pool.query(...).then(...).catch(...)
至
return pool.query(...).then(...).catch(...)
這將回傳您的承諾,以便呼叫者可以.then()在回傳的承諾上使用。
請注意,您的.catch()處理程式addReservation()正在記錄,然后“吃掉”錯誤。您可能應該重新拋出錯誤,以便呼叫者可以看到錯誤:
改變這個:
.catch((e) => console.log(e.message));
對此:
.catch((e) => {
console.log(e.message)
// re-throw the error so it propagates to the caller
throw e;
});
另外,請注意,這res.send(e)可能不會提供太多有用的資訊,因為 Error 物件的大多數屬性都是不可列舉的,因此在res.send()將 Error 物件轉換為 JSON 時不會顯示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/484845.html
標籤:javascript 表示 承诺 路线
上一篇:使用物件屬性創建一個陣列
下一篇:比較2個陣列,如果滿足條件則推送
