2017-08-12 99 views
0

我有appController,userControllernoteController。我想導入userControllernoteControllerappControllerNodejs將控制器導入控制器

首先,這裏是noteController

module.exports = { 
    index: (req, res) => { 
     Note.find({}).sort({ 
      time: -1 
     }).exec((err, notes) => { 
      if (err) throw err; 
      res.send(notes) 
     }); 
    } 
} 

這裏是appController

const noteController = require('./noteController'); 
const userController = require('./userController'); 

module.exports = { 
    show: (req, res) => { 
     noteController.index((err, notes) => { 
      if (err) throw err; 
      res.render('index', { 
       notes: notes 
      }); 
     }); 
    } 
} 

我已經開始這個項目只用notesController終於學會CRUD的節點,但我在這裏有點困惑。在我的appController中,我想索引筆記,並檢查用戶是否已登錄。如果我在此處進行錯誤的編碼練習,請告訴我。

+0

我不認爲你的代碼顯示你想如何處理你的登錄用戶。你的控制器編排的方式不會使它們獨立於請求對象,所以你不能在另一個控制器中使用,而不會傳遞'req'和'res'對象。簽名不符。 – Rowland

+0

我還沒有到用戶部分。我試圖找出一個文件如何檢查用戶是否登錄並根據檢查顯示正確的數據。我沒有得到應該發生視圖渲染的地方。 – Kira

回答

0

根據您的應用程序的大小,您有完全不同的方法來實現您的想法。這就是說,我經常看到的一般慣例是

1)創建用戶控制您的登錄端點,說/api/login

2)創建中間件,以保護那些需要用戶在

要記錄的任何路由3)將用戶標識存儲在請求對象中(#2中的中間件會檢查這個問題並將問題標識存儲在請求對象中,這樣您就可以解碼用戶標識並使用它來查詢數據服務以查找屬於那個用戶)

這就是說,我假設你的應用程序可能不需要驅動我在這個方向。所以這可以爲你工作以及

const userController = (req, res) => { 
    /* Handle your logic here 
    Check that the user credentials match what is in DB 
    Check if the user has notes. 
    This might be two different queries to your DB(User and Notes tables(or collections)) depending on how you structure your schema. 
    You can now respond with the user `specific` notes e.g `res.render('notes', {notes: notes})` 
    */ 
} 

希望這有助於!

+0

現在,我可以看到,我對節點語法的瞭解太低,無法理解。我想我仍然不明白回調和所有這些花哨的東西。多麼令人失望。 – Kira

相關問題