簡體   English   中英

如何在 express 中跨多個 get 請求訪問變量? 有沒有更好的編碼方式?

[英]How to make variables accessible across multiple get requests in express? And is there a better way to code this?

我有以下獲取請求,我在其中調用一堆數據並將其傳遞到我的 EJS 視圖。

router.get('/currentrentals', ensureAuthenticated,  async (req, res) => {

const companies = await Company.getCompanies();
const barges = await Barge.getBarges();
const parishes = await Parish.getParishes();
const states = await State.getStates();
const pickupdropoff = await PickupDropoff.getPickupDropoff();
var notifications = await Notification.getNotifications();
JSON.stringify(barges);
JSON.stringify(companies);
JSON.stringify(parishes);
JSON.stringify(states);
JSON.stringify(pickupdropoff);
JSON.stringify(notifications);
var notifications =  await notifications.sort((a, b) => b.id - a.id).slice(0,3);

res.render('currentrentals', {
    name: req.user.name, companies: companies, barges: barges, parishes: parishes, states: states, pickupdropoff : pickupdropoff, notifications : notifications
});
}
);

兩個問題:

  1. 我有多個需要相同信息的獲取請求。 有沒有辦法讓這些數據在我的整個網站上都可用,這樣我就不必為每個獲取路徑重寫它了?

  2. 有沒有更簡潔的方法來編寫我現有的代碼? 也許循環遍歷它們或類似的東西? 僅供學習之用。

該代碼目前按原樣運行。

謝謝!

如果數據不變,你可以試試這個:

let data = null;

async function getData() {
  if (!data) {
    data = {
      companies: await Company.getCompanies(),
      barges: await Barge.getBarges();
      parishes: await Parish.getParishes(),
      states: await State.getStates(),
      pickupdropoff: await PickupDropoff.getPickupDropoff(),
      notifications: (await Notification.getNotifications()).sort((a, b) => b.id - a.id).slice(0,3)
    };
  }
  return data;
}

router.get('/currentrentals', ensureAuthenticated, async (req, res) => {
    res.render('currentrentals', { name: req.user.name, ...(await getData()) });
  }
);

// other routes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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