diff options
author | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:43:23 -0500 |
---|---|---|
committer | Peter Bengtsson <mail@peterbe.com> | 2020-12-08 14:43:23 -0500 |
commit | 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 (patch) | |
tree | a9ef8ac1e1b8fe4207b6d64d3841bfb8990b6fd0 /files/zh-tw/learn/server-side/express_nodejs | |
parent | 074785cea106179cb3305637055ab0a009ca74f2 (diff) | |
download | translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.gz translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.tar.bz2 translated-content-218934fa2ed1c702a6d3923d2aa2cc6b43c48684.zip |
initial commit
Diffstat (limited to 'files/zh-tw/learn/server-side/express_nodejs')
27 files changed, 6070 insertions, 0 deletions
diff --git a/files/zh-tw/learn/server-side/express_nodejs/deployment/index.html b/files/zh-tw/learn/server-side/express_nodejs/deployment/index.html new file mode 100644 index 0000000000..d7c2089cd1 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/deployment/index.html @@ -0,0 +1,521 @@ +--- +title: 'Express 教學 7: 佈署到生產環境' +slug: Learn/Server-side/Express_Nodejs/deployment +translation_of: Learn/Server-side/Express_Nodejs/deployment +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenu("Learn/Server-side/Express_Nodejs/forms", "Learn/Server-side/Express_Nodejs")}}</div> + +<p class="summary">現在你已經創建(並測試)了一個不錯的 本地圖書館 網站了,你打算把它發佈到一個公共網絡服務器,這樣圖書館管理員和網路上的其他成員就可以訪問它了。這篇文章總結了你可以怎樣找到一台主機部署你的網站,以及你需要為網站準備好佈署到生產環境該做什麼。</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">預備知識:</th> + <td>完成前面所有的指南主題,包括 <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a>.</td> + </tr> + <tr> + <th scope="row">目標:</th> + <td>學習你可以怎樣以及在哪裡部署一個 Express 應用到生產環境。</td> + </tr> + </tbody> +</table> + +<h2 id="概覽">概覽</h2> + +<p>一旦您的站點完成(或完成 “足夠” 以開始公共測試),您將需要將其託管在比您的個人開發計算機,更公開和可訪問的地方。</p> + +<p>到目前為止,您一直在開發環境中工作,使用Express / Node 作為 Web 服務器,將您的站點共享到本地瀏覽器/網路,並使用(不安全的)開發設置運行您的網站,以顯示調試和其他私人信息。在您可以在外部託管網站之前,您首先必須:</p> + +<ul> + <li>選擇託管 Express 應用程序的環境。</li> + <li>對項目設置進行一些更改。</li> + <li>設置生產級別的基礎架構,以服務您的網站。</li> +</ul> + +<p>本教程提供了,有關選擇託管站點的選項的一些指導,簡要概述了為使您的Express 應用程序準備好生產,所需執行的操作,以及一個工作示例,演示如何將 LocalLibrary 網站安裝到 <a href="https://www.heroku.com/">Heroku</a> 雲託管上的服務。</p> + +<p>請記住,您不必使用 Heroku - 還有其他託管服務可用。我們還提供了一個單獨的教程,以展示如何在 <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Installing_on_PWS_Cloud_Foundry">PWS/Cloud Foundry </a>上安裝 LocalLibrary。</p> + +<h2 id="什麼是生產環境?">什麼是生產環境?</h2> + +<p>生產環境是服務器計算機提供的環境,您可以在其中運行網站,以供外部使用。環境包括:</p> + +<ul> + <li>網站運行的計算機硬件。</li> + <li>操作系統(例如 Linux 或 Windows)。</li> + <li>編程語言運行庫和框架庫,在其上編寫您的網站。</li> + <li>Web 服務器基礎結構,可能包含 Web 服務器,反向代理,負載平衡器等。</li> + <li>您的網站所依賴的數據庫。</li> +</ul> + +<p>服務器計算機,可以位於您的場所,並通過快速鏈接,連接到 Internet,但使用 “託管在雲上” 的計算機更為常見。這實際上意味著,您的代碼運行在託管公司的數據中心的某台遠程計算機(或可能是“虛擬”計算機)。遠程服務器,通常會以特定價格提供互聯網連接,和一些保證級別的計算資源(例如CPU,RAM,存儲器等)。</p> + +<p>這種可遠程訪問的計算/網絡硬件,稱為基礎架構即服務(IaaS)。許多 IaaS 供應商,提供預安裝特定操作系統的選項,您必須在其上,安裝生產環境的其他組件。其他供應商,允許您選擇功能更全面的環境,可能包括完整的 node 設置。</p> + +<div class="note"> +<p><strong>注意:</strong> 預構建環境,可以使您的網站設置變得非常簡單,因為它們會減少配置,但可用選項可能會限制您使用不熟悉的服務器(或其他組件),並且可能基於較舊版本的操作系統。通常最好自己安裝組件,以便獲得所需的組件,並且當您需要升級系統的某些部分時,您可以知道從哪裡開始!</p> +</div> + +<p>其他託管服務提供商,支持 Express 作為平台即服務(PaaS)產品的一部分。使用此類託管時,您無需擔心大多數生產環境(服務器,負載平衡器等),因為主機平台會為您處理這些問題。這使得部署非常簡單,因為您只需要專注於 Web 應用程序,而不是任何其他服務器基礎結構。</p> + +<p>一些開發人員選擇 IaaS ,相對於 PaaS ,IaaS 提供更高靈活性,而其他開發人員偏好 PaaS 的降低維護開銷,和更輕鬆的擴展性。當您在一開始使用時,在 PaaS 系統上設置您的網站,要容易得多,因此我們將在本教程中使用 PaaS。</p> + +<div class="note"> +<p><strong>提示:</strong> 如果您選擇 Node/Express 友好的託管服務提供商,他們應該提供,有關如何使用 Web 服務器,應用程序服務器,反向代理等不同配置,來設置 Express 網站的說明。例如,在<a href="https://www.digitalocean.com/community/tutorials?q=node"> Digital Ocean</a> 的node 社區文檔中,有許多各種配置的手把手指南。</p> +</div> + +<h2 id="選擇一個主機供應商">選擇一個主機供應商</h2> + +<p>眾所周知,眾多託管服務提供商,都積極支持或與 Node(和Express)合作。這些供應商提供不同類型的環境(IaaS,PaaS),以及不同價格的不同級別的計算和網絡資源。</p> + +<div class="note"> +<p><strong>提示:</strong> 有很多託管解決方案,他們的服務和定價,可能會隨著時間而改變。雖然我們在下面介紹幾個選項,但在選擇託管服務提供商之前,有必要自己進行互聯網搜索。</p> +</div> + +<p>選擇主機時需要考慮的一些事項:</p> + +<ul> + <li>您的網站可能有多忙,以及滿足該需求所需的數據,和計算資源的成本。</li> + <li>水平擴展(添加更多機器)和垂直擴展(升級到更強大的機器)的支持級別,以及這樣做的成本。</li> + <li>供應商有數據中心的地方,因此訪問可能是最快的。</li> + <li>主機正常運行時間和停機時間的歷史表現。</li> + <li>用於管理站點的工具 - 易於使用且安全(例如 SFTP 與 FTP)。</li> + <li>用於監控服務器的內置框架。</li> + <li>已知限制。有些主機會故意阻止某些服務(例如電子郵件)。其他在某些價格層中,僅提供一定數小時的 “實時時間”,或者僅提供少量存儲空間。</li> + <li>額外的好處。一些提供商將提供免費域名和 SSL 證書支持,否則您將不得不為此另外支付費用。</li> + <li>您所依賴的“免費”等級,是否會隨著時間的推移而過期,以及遷移到更昂貴等級的成本,是否意味著您最好在一開始就使用其他服務!</li> +</ul> + +<p>當你剛開始時,好消息是有很多網站提供“免費”的計算環境,儘管有一些條件。例如, <a href="https://www.heroku.com/">Heroku</a> “永遠” 提供免費但資源有限的 PaaS 環境,而 <a href="http://docs.aws.amazon.com/awsaccountbilling/latest/aboutv2/billing-free-tier.html">Amazon Web Services</a>, <a href="https://azure.microsoft.com/en-us/pricing/details/app-service/">Microsoft Azure</a> 和開源選項 <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Installing_on_PWS_Cloud_Foundry">PWS/Cloud Foundry</a> 在您第一次加入時,提供免費信用額度。</p> + +<p>許多提供商還擁有“基本”層,可提供更多有用的計算能力,和更少的限制。舉例來說, <a href="https://www.digitalocean.com/">Digital Ocean</a> 是一個流行的託管服務提供商,它提供了一個相對便宜的基本計算層(在本教程寫作時,是每月5美元的較低範圍)。</p> + +<div class="note"> +<p><strong>注意:</strong> 請記住,價格不是唯一的選擇標準。如果您的網站成功,可能會發現可擴展性是最重要的考慮因素。</p> +</div> + +<h2 id="準備好發布你的網站">準備好發布你的網站</h2> + +<p>發佈網站時,要考慮的主要問題是網絡安全性和性能。至少,您需要刪除開發期間,錯誤頁面上包含的堆棧跟踪,整理日誌記錄,並設置適當的標頭,以避免許多常見的安全威脅。</p> + +<p>在以下小節中,我們概述了您應該對應用進行的、最重要的更改。</p> + +<div class="note"> +<p><strong>提示:</strong> Express文檔中還有其他有用的提示 - 請參閱“<a href="https://expressjs.com/en/advanced/best-practice-performance.html">生產最佳實踐:性能和可靠性</a>”,以及“<a href="https://expressjs.com/en/advanced/best-practice-security.html">生產最佳實踐:安全性</a>”。</p> +</div> + +<h3 id="設置_NODE_ENV_為_'production'">設置 NODE_ENV 為 'production'</h3> + +<p>我們可以通過將 <code>NODE_ENV</code> 環境變量,設置為 production ,來刪除錯誤頁面中的堆棧跟踪(默認設置為 “development” )。除了生成較為不詳細的錯誤消息之外,還要將變量設置為生產緩存視圖模板,和從 CSS 擴展生成的 CSS 文件。測試表明,將<code>NODE_ENV</code>設置為生產,可以將應用程序性能提高三倍!</p> + +<p>可以使用導出或環境文件,或使用 OS 初始化系統,以進行此更改。</p> + +<div class="note"> +<p><strong>注意:</strong> 這實際上是在環境設置,而不是應用中所做的更改,但重要的是,要注意這裡!我們將在下面,展示我們的託管示例要如何設置。</p> +</div> + +<h3 id="Log_appropriately">Log appropriately</h3> + +<p>記錄呼叫會對高流量網站產生影響。在生產環境中,您可能需要記錄網站活動(例如,跟踪流量,或記錄API調用),但您應嘗試最小化為調試目的而添加的日誌記錄量。</p> + +<p>在生產環境中,最小化“調試”日誌記錄的一種方法,是使用類似調試 <a href="https://www.npmjs.com/package/debug">debug </a> 的模塊,允許您通過設置環境變量,來控制執行的日誌記錄。例如,下面的代碼片段,顯示如何設置 “author” 日誌記錄。調試變量使用名稱 “author” 聲明,並且將自動顯示,來自此對象的所有日誌的前綴 “author”。</p> + +<pre class="brush: js"><strong>var debug = require('debug')('author');</strong> + +// Display Author update form on GET +exports.author_update_get = function(req, res, next) { + + req.sanitize('id').escape().trim(); + Author.findById(req.params.id, function(err, author) { + if (err) { +<strong> debug('update error:' + err);</strong> + return next(err); + } + //On success + res.render('author_form', { title: 'Update Author', author: author }); + }); + +};</pre> + +<p>然後,您可以通過在 <code>DEBUG </code>環境變量中,將它們指定為逗號分隔列表,來啟用特定日誌集。您可以設置顯示作者和書籍日誌的變量,如圖所示(也支持通配符)。</p> + +<pre class="brush: bash">#Windows +set DEBUG=author,book + +#Linux +export DEBUG="author,book" +</pre> + +<div class="note"> +<p><strong>挑戰:</strong> 調用<code>debug</code>可以替換您以前使用 <code>console.log()</code>或<code>console.error()</code>執行的日誌記錄。通過調試模塊 <a href="https://www.npmjs.com/package/debug">debug </a>進行日誌記錄,替換代碼中的所有<code>console.log()</code>調用。通過設置 DEBUG 變量,並在其中記錄對日誌記錄的影響,在開發環境中,打開和關閉日誌記錄。</p> +</div> + +<p>如果您需要記錄網站活動,可以使用 Winston 或 Bunyan 等日誌庫。有關此主題的更多信息,請參閱:<a href="https://expressjs.com/en/advanced/best-practice-performance.html">生產最佳實踐:性能和可靠性</a>。</p> + +<h3 id="使用_gzipdeflate_壓縮響應">使用 gzip/deflate 壓縮響應</h3> + +<p>Web 服務器,通常可以壓縮發送回客戶端的 HTTP 響應,從而顯著減少客戶端獲取和加載頁面所需的時間。使用的壓縮方法,取決於客戶端在請求中支持的解壓縮方法(如果不支持壓縮方法,則響應將以未壓縮的方式發送)。</p> + +<p>您可以使用壓縮中間件 <a href="https://www.npmjs.com/package/compression">compression</a>,將其添加到您的站點。通過在項目的根目錄下,運行以下命令,將其安裝到項目中。</p> + +<pre class="brush: bash">npm install compression</pre> + +<p>打開<strong>./app.js</strong>,並導入壓縮庫,如圖所示。使用<code> use()</code>方法,將壓縮庫添加到中間件鏈(這應該出現在您想要壓縮的任何路由之前 - 在本教程這種情況下,全部都是!)</p> + +<pre class="brush: js">var catalogRouter = require('./routes/catalog'); //Import routes for "catalog" area of site +<strong>var compression = require('compression');</strong> + +// Create the Express application object +var app = express(); + +... + +<strong>app.use(compression()); //Compress all routes</strong> + +app.use(express.static(path.join(__dirname, 'public'))); + +app.use('/', indexRouter); +app.use('/users', usersRouter); +app.use('/catalog', catalogRouter); // Add catalog routes to middleware chain. + +... +</pre> + +<div class="note"> +<p><strong>注意</strong>: 對於生產中流量較大的網站,您不會使用此中間件。相反,你會使用像 Nginx 這樣的反向代理。</p> +</div> + +<h3 id="使用_Helmet_避免被常見漏洞侵襲">使用 Helmet 避免被常見漏洞侵襲</h3> + +<p><a href="https://www.npmjs.com/package/helmet">Helmet</a> 是一個中間件包,可以通過設置適當的 HTTP 標頭,來幫助保護您的應用,免受一些眾所周知的 Web 漏洞的影響(有關它設置的標頭/防護漏洞的詳細信息,請參閱文檔 <a href="https://helmetjs.github.io/docs/">docs</a>) 。</p> + +<p>通過在項目的根目錄下,運行以下命令,將其安裝到項目中。</p> + +<pre class="brush: bash">npm install helmet +</pre> + +<p>打開<strong>./app.js</strong>,並導入如圖所示的 helmet 庫。然後使用<code>use()</code>方法,將模塊添加到中間件鏈。</p> + +<pre class="brush: js">var compression = require('compression'); +<strong>var helmet = require('helmet'); +</strong> +// Create the Express application object +var app = express(); + +<strong>app.use(helmet())</strong>; +...</pre> + +<div class="note"> +<p id="production-best-practices-performance-and-reliability"><strong>注意:</strong> 上面的命令,添加了對大多數站點有意義的可用標頭子集。您可以按照 <a href="https://www.npmjs.com/package/helmet">npm </a>上的說明,根據需要添加/禁用特定標頭。</p> +</div> + +<h2 id="例子:在_Heroku_上安裝本地圖書館">例子:在 Heroku 上安裝本地圖書館</h2> + +<p>本節提供如何在 <a href="http://heroku.com">Heroku PaaS cloud</a> 雲上安裝 LocalLibrary 的實際演示。</p> + +<h3 id="為什麼選擇_Heroku">為什麼選擇 Heroku?</h3> + +<p>Heroku 是運行時間最長,且最受歡迎的基於雲的 PaaS 服務之一。它最初只支持 Ruby 應用程序,但現在可用於託管來自許多編程環境的應用程序,包括 Node(以及Express)!</p> + +<p>我們選擇使用 Heroku 有以下幾個原因:</p> + +<ul> + <li>Heroku 有一個免費套餐 <a href="https://www.heroku.com/pricing">free tier</a>(儘管有一些限制)。</li> + <li>作為 PaaS,Heroku 為我們提供了大量的 Web 基礎架構。這使得入門更加容易,因為您不必擔心服務器,負載平衡器,反向代理,崩潰時重新啟動網站,或者 Heroku 為我們提供的任何其他 Web 基礎結構。</li> + <li>雖然它確實有一些限制,但這些不會影響這個特定的應用程序。例如: + <ul> + <li>Heroku 只提供短期存儲,因此用戶上傳的文件無法安全地存儲在 Heroku本身。</li> + <li>如果半小時內沒有請求,免費套餐將使不活動的網絡應用程序進入睡眠。然後,該網站可能需要幾秒鐘才能被喚醒。</li> + <li>免費套餐將您網站運行的時間,限制為每月一定的小時數(不包括網站“睡著”的時間)。這對於低使用/演示站點來說很好,但如果需要100%的正常運行時間,則不適用。</li> + <li>Heroku 官方文檔 <a href="https://devcenter.heroku.com/articles/limits">Limits </a>中列出的其他限制。</li> + </ul> + </li> + <li>大多數情況下,它只是可以工作,如果你最終喜歡它,並希望升級,那麼擴展你的應用程序非常容易。</li> +</ul> + +<p>雖然 Heroku 非常適合舉辦此演示,但它可能並不適合您的真實網站。 Heroku 可以輕鬆設置和擴展,但代價是靈活性較低,而且一旦退出免費套餐,可能會花費更多。</p> + +<h3 id="Heroku_如何工作">Heroku 如何工作?</h3> + +<p>Heroku在一個或多個 "<a href="https://devcenter.heroku.com/articles/dynos">Dynos</a>" 中運行網站,這些 “Dynos” 是獨立的虛擬化Unix容器,提供運行應用程序所需的環境。 Dynos 是完全隔離的,並且有一個短暫的文件系統(一個短暫的文件系統,每次dyno重新啟動時都會清理/清空)。 dynos 默認共享的唯一內容,是應用程序配置變量 <a href="https://devcenter.heroku.com/articles/config-vars">configuration variables</a>。 Heroku 內部使用負載均衡器,將Web流量分配給所有 “web” dynos。由於它們之間沒有任何共享,Heroku 可以通過添加更多 dynos,來水平擴展應用程序(當然,您可能還需要擴展數據庫,以接受其他連接)。</p> + +<p>由於文件系統是短暫的,因此無法直接安裝應用程序所需的服務(例如數據庫,隊列,緩存系統,存儲,電子郵件服務等)。相反,Heroku Web應用程序使用 Heroku 或第三方作為獨立“附加組件”提供的支持服務。連接到Web應用程序後,可以通過環境變量,在Web應用程序中訪問附加服務。</p> + +<p>為了執行您的應用程序,Heroku 需要能夠設置適當的環境和依賴關係,並了解它是如何啟動的。對於 Node 應用程序,它所需的所有信息都是從 <strong>package.json</strong>文件中獲取的。</p> + +<p>開發人員使用特殊的客戶端應用程序/終端,與 Heroku 交互,這很像 Unix bash 腳本。這允許您上傳存儲在 git 儲存庫中的代碼,檢查正在運行的進程,查看日誌,設置配置變量等等!</p> + +<p>為了讓我們的應用程序在 Heroku 上工作,我們需要將我們的 Express Web 應用程序放入 git 儲存庫,並對 package.json 進行一些小的更改。完成後,我們可以設置Heroku 帳戶,獲取 Heroku 客戶端,並使用它來安裝我們的網站。</p> + +<p>這是您開始教程所需的全部概述(有關更全面的指南,請參閱帶有 Node.js 的<a href="https://devcenter.heroku.com/articles/getting-started-with-nodejs">Heroku</a> 入門)。</p> + +<h3 id="在_Github_上創建一個應用倉庫">在 Github 上創建一個應用倉庫</h3> + +<p>Heroku 與 <strong>git</strong> 源代碼版本控制系統緊密集成,使用它來上傳/同步您對實時運行系統所做的任何更改。它通過添加一個名為 heroku 的新 Heroku“遠程”儲存庫,來指向您在Heroku雲上的源儲存庫。在開發期間,您使用 git 在“主”儲存庫 master 中儲存更改。如果要部署站點,請將更改同步到 Heroku 存儲庫。</p> + +<div class="note"> +<p><strong>注意:</strong> 如果您習慣於遵循良好的軟件開發實踐,那麼您可能已經在使用 git 或其他一些 SCM 系統。如果您已有 git 儲存庫,則可以跳過此步驟。</p> +</div> + +<p>有很多方法可以使用git,但最簡單的方法之一,是首先在 <a href="https://github.com/">GitHub </a>上建立一個帳戶,在那裡創建儲存庫,然後在本地同步它:</p> + +<ol> + <li>訪問 <a href="https://github.com/">https://github.com/</a> 並創建一個帳戶。</li> + <li>登錄後,單擊頂部工具欄中的 + 號鏈接,然後選擇新建儲存庫 <strong>New repository</strong>。</li> + <li>填寫此表單上的所有字段。雖然這些不是強制性的,但強烈建議使用它們。 + <ul> + <li>輸入新的存儲庫名稱(例如,express-locallibrary-tutorial)和描述(例如 “以Express(node)編寫的本地圖書館網站”)。</li> + <li>在 Add .gitignore 選擇列表中選擇 <strong>Node</strong>。</li> + <li>在添加許可證 Add license 選擇列表中,選擇您偏好的許可證。</li> + <li>點選 使用自述文件初始化此儲存庫 <strong>Initialize this repository with a README</strong>.</li> + </ul> + </li> + <li>按 <strong>Create repository</strong>.</li> + <li>單擊新倉庫頁面上的綠色“克隆或下載”按鈕 "<strong>Clone or download</strong>" 。</li> + <li>從顯示的對話框的文本字段,複製 URL值(它應該類似於:<strong>https://github.com/<em><your_git_user_id></em>/express-locallibrary-tutorial.git</strong>)。</li> +</ol> + +<p>現在創建了儲存庫(“repo”),我們將要在本地計算機上克隆它:</p> + +<ol> + <li>為您的本地計算機安裝 git(您可以在<a href="https://git-scm.com/downloads">此處找到不同平台的版本</a>)。<br> + </li> + <li>打開命令提示符/終端,並使用您在上面複製的 URL ,克隆儲存庫: + <pre class="brush: bash">git clone https://github.com/<strong><em><your_git_user_id></em></strong>/express-locallibrary-tutorial.git +</pre> + 這將在當前時間點之後,創建儲存庫。</li> + <li>到新的儲存庫。 + <pre class="brush: bash">cd express-locallibrary-tutorial</pre> + </li> +</ol> + +<p>最後一步,是複制你的應用程序,然後使用 git ,將文件添加到你的倉庫:</p> + +<ol> + <li>將Express應用程序,複製到此文件夾中(不包括 <strong>/node_modules</strong>,其中包含您應根據需要,從 NPM 獲取的依賴項文件)。</li> + <li>打開命令提示符/終端,並使用 <code>add </code>命令,將所有文件添加到 git。</li> + <li> + <pre class="brush: bash">git add -A +</pre> + </li> + <li>使用 status 命令,檢查要添加的所有文件是否正確(您希望包含源文件,而不是二進製文件,臨時文件等)。它應該看起來有點像下面的列表。 + <pre>> git status +On branch master +Your branch is up-to-date with 'origin/master'. +Changes to be committed: + (use "git reset HEAD <file>..." to unstage) + + new file: ...</pre> + </li> + <li>如果您滿意,請將文件提交到本地儲存庫: + <pre class="brush: bash">git commit -m "First version of application moved into github"</pre> + </li> + <li>然後使用以下內容,將本地儲存庫同步到 Github 網站: + <pre>git push origin master</pre> + </li> +</ol> + +<p>完成此操作後,您應該可以返回創建儲存庫的 Github 上的頁面,刷新頁面,並查看您的整個應用程序現已上傳。使用此添加/提交/推送循環,您可以在文件更改時,繼續更新儲存庫。</p> + +<div class="note"> +<p><strong>提示:</strong> 這是備份你的“vanilla”項目的好時機 - 雖然我們將在以下部分中進行的一些更改,可能對任何平台(或開發)上的部署有用,而一些其他的更改可能沒有用。</p> + +<p>執行此操作的最佳方法,是使用 git 來管理您的修訂。使用 git,您不僅可以回到特定的舊版本,而且可以在生產變更的單獨“分支”中進行維護,並選擇在生產和開發分支之間移動的任何更改。<a href="https://help.github.com/articles/good-resources-for-learning-git-and-github/">學習Git</a>非常值得,但超出了本主題的範圍。</p> + +<p>最簡單的方法,是將文件複製到另一個位置。以您對 git 了解,使用最符合的方法!</p> +</div> + +<h3 id="更新_Heroku_的應用程序">更新 Heroku 的應用程序</h3> + +<p>本節介紹了您需要對 LocalLibrary 應用程序進行的更改,以使其在 Heroku 上運行。</p> + +<h4 id="設置_node_版本">設置 node 版本</h4> + +<p><strong>package.json</strong> 包含解決應用程序依賴項所需的所有內容,以及啟動站點時,應啟動的文件。 Heroku 檢測到此文件的存在,並將使用它來配置您的應用程序環境。</p> + +<p>我們當前的 <strong>package.json</strong> 中,缺少的唯一有用信息,是 node 的版本。我們可以通過輸入命令,找到我們用於開發的 node 版本:</p> + +<pre class="brush: bash">>node --version +v8.9.1</pre> + +<p>打開 <strong>package.json</strong>,並將此信息添加為 <strong>engines > node</strong> 部分,如圖所示(使用系統的版本號)。</p> + +<pre class="brush: json">{ + "name": "express-locallibrary-tutorial", + "version": "0.0.0", +<strong> "engines": { + "node": "8.9.1" + },</strong> + "private": true, + ... +</pre> + +<h4 id="數據庫配置">數據庫配置</h4> + +<p>到目前為止,在本教程中,我們使用了一個硬編碼到 <strong>app.js</strong> 的單個數據庫。通常我們希望,能夠為生產和開發創建不同的數據庫,接下來我們將修改 LocalLibrary 網站,以從 OS 環境獲取數據庫 URI(如果已定義),否則使用我們的開發數據庫。</p> + +<p>打開 <strong>app.js</strong>,並找到設置 mongoDB 連接變量的行。它看起來像這樣:</p> + +<pre class="brush: js">var mongoDB = 'mongodb://your_user_id:your_password@ds119748.mlab.com:19748/local_library';</pre> + +<p>使用以下代碼替換該行,該代碼使用 <code>process.env.MONGODB_URI </code>從名為 <code>MONGODB_URI </code>的環境變量中,獲取連接字符串(如果已設置)(使用您自己的數據庫URL,而不是下面的佔位符。)</p> + +<pre class="brush: js">var mongoDB = <strong>process.env.MONGODB_URI</strong> || 'mongodb://your_user_id:your_password@ds119748.mlab.com:19748/local_library'; +</pre> + +<h4 id="安裝依賴並重新測試">安裝依賴並重新測試</h4> + +<p>在我們繼續之前,讓我們再次測試該網站,並確保它不受我們的任何更改的影響。</p> + +<p>首先,我們需要獲取我們的依賴項(你會記得,我們沒有將 <strong>node_modules</strong>文件夾,複製到我們的 git 樹中)。您可以通過在項目根目錄的終端中,運行以下命令來執行此操作:</p> + +<pre class="brush: bash">npm install +</pre> + +<p>現在運行該站點(請參閱<a href="/zh-TW/docs/Learn/Server-side/Express_Nodejs/routes#Testing_the_routes">測試路由</a>的相關命令),並檢查該站點,是否仍按預期運行。</p> + +<h4 id="將更改保存到_Github">將更改保存到 Github</h4> + +<p>接下來,讓我們將所有更改保存到 Github。在終端中(在我們的儲存庫中),輸入以下命令:</p> + +<pre class="brush: bash">git add -A +git commit -m "Added files and changes required for deployment to heroku" +git push origin master</pre> + +<p>我們現在應該準備開始在 Heroku 上,部署 LocalLibrary。</p> + +<h3 id="獲取一個_Heroku_帳戶">獲取一個 Heroku 帳戶</h3> + +<p>要開始使用 Heroku,您首先需要創建一個帳戶(如果您已經擁有一個帳戶,並安裝了 Heroku 客戶端,請跳過創建並上傳網站):</p> + +<ul> + <li>訪問 <a href="https://www.heroku.com/">www.heroku.com</a> 並單擊免費註冊按鈕 <strong>SIGN UP FOR FREE</strong></li> + <li>輸入您的詳細信息,然後按 <strong>CREATE FREE ACCOUNT</strong>。系統會要求您,檢查帳戶中是否有註冊電子郵件。</li> + <li>單擊註冊電子郵件中的帳戶激活鏈接。您將在網絡瀏覽器上收回您的帳戶。</li> + <li>輸入您的密碼,然後單擊 <strong>SET PASSWORD AND LOGIN</strong>.</li> + <li>然後,您將登錄並進入Heroku儀表板: <a href="https://dashboard.heroku.com/apps">https://dashboard.heroku.com/apps</a>.</li> +</ul> + +<h3 id="安裝客戶端">安裝客戶端</h3> + +<p>按照 <a href="https://devcenter.heroku.com/articles/getting-started-with-python#set-up">Heroku 上的說明</a>,下載並安裝 Heroku 客戶端。</p> + +<p>安裝客戶端后,您將能夠運行命令。例如,要獲得客戶端的幫助說明:</p> + +<pre class="brush: bash">heroku help +</pre> + +<h3 id="創建並上傳網站">創建並上傳網站</h3> + +<p>要創建應用程序,我們在儲存庫的根目錄中,運行 “create” 命令。這將在我們的本地git 環境中,創建一個名為 heroku 的 git remote(“指向遠程儲存庫的指針”)。</p> + +<pre class="brush: bash">heroku create</pre> + +<div class="note"> +<p><strong>注意:</strong> 如果您願意,可以在“創建”create 之後指定遠程儲存庫的命名。如果你不這樣做,你會得到一個隨機的名字。該名稱用於默認 URL。</p> +</div> + +<p>然後,我們可以將我們的應用程序,推送到 Heroku 儲存庫,如下所示。這將上傳應用程序,獲取所有依賴項,將其打包到 dyno 中,然後啟動該站點。</p> + +<pre class="brush: bash">git push heroku master</pre> + +<p>如果我們很幸運,該應用程序現在正在網站上“運行”。要打開瀏覽器並運行新網站,請使用以下命令:</p> + +<pre class="brush: bash">heroku open</pre> + +<div class="note"> +<p><strong>注意</strong>: 該站點將使用我們的開發數據庫運行。創建一些書本和其他對象,並檢查該網站是否按預期運行。在下一節中,我們將其設置為使用我們的新數據庫。</p> +</div> + +<h3 id="設定配置變量">設定配置變量</h3> + +<p>您將從前一節回憶起,我們需要將 NODE_ENV 設置為 'production',以便提高性能,並生成更簡潔的錯誤消息。我們通過輸入以下命令,來完成此操作:</p> + +<pre class="brush: bash">>heroku config:set NODE_ENV='production' +Setting NODE_ENV and restarting limitless-tor-18923... done, v13 +NODE_ENV: production +</pre> + +<p>我們還應該使用單獨的數據庫進行生產,在<strong>MONGODB_URI</strong>環境變量中,設置其URI。您可以完全按照<a href="/zh-TW/docs/Learn/Server-side/Express_Nodejs/mongoose#Setting_up_the_MongoDB_database">我們原來的方式</a>,設置新數據庫和數據庫用戶,並獲取其URI。您可以如下圖所示設置URI(顯然,要使用您自己的URI!)</p> + +<pre class="brush: bash">>heroku config:set <strong>MONGODB_URI</strong>='mongodb://your_user:your_password@ds139278.mlab.com:39278/local_library_production' +Setting MONGODB_URI and restarting limitless-tor-18923... done, v13 +MONGODB_URI: mongodb://your_user:your_password@ds139278.mlab.com:39278/local_library_production +</pre> + +<p>您可以使用 <code>heroku config </code>命令,隨時檢查配置變量 - 立即嘗試:</p> + +<pre class="brush: bash">>heroku config +=== limitless-tor-18923 Config Vars +MONGODB_URI: mongodb://your_user:your_password@ds139278.mlab.com:39278/local_library_production +NODE_ENV: production +</pre> + +<p>Heroku 會在更新變量時,重新啟動應用程序。如果您現在檢查主頁,它應該顯示對象計數的零值,因為上面的更改,意味著我們現在正在使用新的(空)數據庫。</p> + +<h3 id="管理附加組件">管理附加組件</h3> + +<p>Heroku 使用獨立的附加組件,為應用程序提供支持服務 - 例如電子郵件或數據庫服務。我們不在本網站中使用任何插件,但它們是使用 Heroku 的重要部分,因此您可能需要查看主題 - <a href="https://devcenter.heroku.com/articles/managing-add-ons">管理插件(Heroku 官方文件)</a>。</p> + +<h3 id="除錯">除錯</h3> + +<p>Heroku 客戶端提供了一些除錯工具:</p> + +<pre class="brush: bash">heroku logs # Show current logs +heroku logs --tail # Show current logs and keep updating with any new results +heroku ps #Display dyno status +</pre> + +<ul> +</ul> + +<h2 id="總結">總結</h2> + +<p>本教程介紹在生產環境中,如何配置 Express 應用。是Express系列教程的最後一個。我們希望你覺得這些教程有用。你可以在 <a href="https://github.com/mdn/express-locallibrary-tutorial">Github </a>上取得完整的源碼。</p> + +<h2 id="相關鏈接">相關鏈接</h2> + +<ul> + <li id="production-best-practices-performance-and-reliability"><a href="https://expressjs.com/en/advanced/best-practice-performance.html">Production best practices: performance and reliability</a> (Express docs)</li> + <li><a href="https://expressjs.com/en/advanced/best-practice-security.html">Production Best Practices: Security</a> (Express docs)</li> + <li>Heroku + <ul> + <li><a href="https://devcenter.heroku.com/articles/getting-started-with-nodejs">Getting Started on Heroku with Node.js</a> (Heroku docs)</li> + <li><a href="https://devcenter.heroku.com/articles/deploying-nodejs">Deploying Node.js Applications on Heroku</a> (Heroku docs)</li> + <li><a href="https://devcenter.heroku.com/articles/nodejs-support">Heroku Node.js Support</a> (Heroku docs)</li> + <li><a href="https://devcenter.heroku.com/articles/node-concurrency">Optimizing Node.js Application Concurrency</a> (Heroku docs)</li> + <li><a href="https://devcenter.heroku.com/articles/how-heroku-works">How Heroku works</a> (Heroku docs)</li> + <li><a href="https://devcenter.heroku.com/articles/dynos">Dynos and the Dyno Manager</a> (Heroku docs)</li> + <li><a href="https://devcenter.heroku.com/articles/config-vars">Configuration and Config Vars</a> (Heroku docs)</li> + <li><a href="https://devcenter.heroku.com/articles/limits">Limits</a> (Heroku docs)</li> + </ul> + </li> + <li>Digital Ocean + <ul> + <li><a href="https://www.digitalocean.com/community/tutorials?q=express">Express</a> tutorials</li> + <li><a href="https://www.digitalocean.com/community/tutorials?q=node.js">Node.js</a> tutorials </li> + </ul> + </li> +</ul> + +<p>{{PreviousMenu("Learn/Server-side/Express_Nodejs/forms", "Learn/Server-side/Express_Nodejs")}}</p> + +<p> </p> + +<h2 id="本教學鏈接">本教學鏈接</h2> + +<ul> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node introduction</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">Setting up a Node (Express) development environment</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Express Tutorial: The Local Library website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Express Tutorial Part 2: Creating a skeleton website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Express Tutorial Part 3: Using a Database (with Mongoose)</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/routes">Express Tutorial Part 4: Routes and controllers</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/deployment">Express Tutorial Part 7: Deploying to production</a></li> +</ul> + +<p> </p> diff --git a/files/zh-tw/learn/server-side/express_nodejs/development_environment/index.html b/files/zh-tw/learn/server-side/express_nodejs/development_environment/index.html new file mode 100644 index 0000000000..3e556ada3a --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/development_environment/index.html @@ -0,0 +1,385 @@ +--- +title: Setting up a Node development environment +slug: Learn/Server-side/Express_Nodejs/development_environment +translation_of: Learn/Server-side/Express_Nodejs/development_environment +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}</div> + +<p class="summary">現在你已經了解Express的目的了,接下來繼續說明如何設定和測試 Windows、Linux (Ubuntu)和Mac OS X上的Node/Express開發環境。不管你用的是什麼作業系統,你都能在本文中找到開發Express應用的入門需知。</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">前置需求:</th> + <td>了解如何開啟terminal / command line. 了解如何在開發系統上安裝套件。</td> + </tr> + <tr> + <th scope="row">目標:</th> + <td>在你的電腦上設定Express(X.XX)開發環境。</td> + </tr> + </tbody> +</table> + +<h2 id="Express_開發環境概覽">Express 開發環境概覽</h2> + +<p>為了使你能快速的開發web應用,<em>Node</em> 和 <em>Express</em> 非常容易安裝,這個部分說明哪些工具是需要的、在Ubuntu、macOS和Windows中安裝Node和Express的最簡單方法、展示如何測試安裝成功與否。</p> + +<h3 id="什麼是Express開發環境">什麼是Express開發環境?</h3> + +<p><em>Express</em> 開發環境包含 <em>Nodejs、</em><em>NPM </em>套件管理器的安裝, 還有 <em>Express Application </em>產生器(可選)<em>。</em></p> + +<p><em>Node </em>和 <em>NPM</em> 套件管理器會從準備好的 binary package、安裝檔、 作業系統的套件管理器或是從源檔一起安裝。接著 <em>Express </em>會透過 NPM 進行安裝,成為你所有個別 Express web 應用的依賴項(以及其他函式庫,如模板引擎,資料庫驅動程式,身份驗證中間層,用於提供靜態文件的中間件等)</p> + +<p>NPM 也可用來安裝 Express 應用程式產生器(全域用),一個方便的工具幫助你創造符合 <a href="https://developer.mozilla.org/en-US/Apps/Fundamentals/Modern_web_app_architecture/MVC_architecture">MVC模式</a>的 Express web app 骨架。你不一定要使用應用程式產生器,因為每個Express應用程式不需要擁有同樣的檔案結構或依賴項。但為了專注於學習本身以及習慣模組化架構,我們會在接下來的教學中使用它。</p> + +<div class="note"> +<p><strong>注意:</strong> 與其他不包含單獨的web開發伺服器的Web框架不同。 在Node / Express中,Web應用程式創建並運行自己的Web伺服器!</p> +</div> + +<p>典型的開發環境還包含其他工具,例如:編輯程式碼使用的<a href="https://developer.mozilla.org/en-US/docs/Learn/Common_questions/Available_text_editors">文字編輯器</a>、IDE,進行版本控置管理不同版本程式碼的<a href="/zh-TW/docs/Glossary/Git">Git</a>。這邊假設你已經有這種工具了(尤其是文字編輯器)</p> + +<h3 id="哪些作業系統有支援">哪些作業系統有支援?</h3> + +<p>Node 可以執行在 Windows、macOS、各種 Linux、Docker 等等(nodejs 的<a href="https://nodejs.org/en/download/">下載</a>頁面有完整的列表),在開發階段中個人電腦應該都有足夠的效能來執行 Node 。Express 執行在 Node 環境中,所以也能所有有安裝Node的平台上執行。</p> + +<p>在這份教學中我們提供 Windows、macOS 和 Ubuntu Linux 的 Node 安裝教學。</p> + +<h3 id="該用什麼版本的_NodeExpress">該用什麼版本的 Node/Express?</h3> + +<p>Node 有許多<a href="https://nodejs.org/en/blog/release/">版本</a>,更新的版本代表著 bug 的修復、支援更新版本的 ECMAScript(JavaScript)標準和更好的 Node APIs 。</p> + +<p>基本上你應該使用最新的 LTS 版本(<em>long-term supported,</em>長期維護版)。這種版本比『Current』版本更穩定而且還擁有最新的功能及持續性的更新維護。除非LTS不支援你需要的功能才使用『Current』版本。</p> + +<p>而 Express ?永遠使用最新版!</p> + +<h3 id="關於資料庫和其他依賴項呢">關於資料庫和其他依賴項呢?</h3> + +<p>諸如資料庫、模版引擎、驗證引擎等等都屬於應用程式的一部分,這些依賴項會透過NPM導入應用程式環境中,在後續的章節將會進一步探討。</p> + +<h2 id="安裝Node">安裝Node</h2> + +<p>為了使用Express,首先要在你的電腦上安裝Node和<a href="https://docs.npmjs.com/">Node Package Manager (NPM)</a>。接下來用最簡單的方法在 Ubuntu Linux 16.04、 macOS和 Windows 10上安裝Nodejs的 Long Term Supported (LTS)版本吧</p> + +<div class="note"> +<p>以下的部分用最簡單的方法在上述的作業系統中安裝Node和NPM。如果你使用其他作業系統或想看看其他平台的安裝方式,請查閱<a href="https://nodejs.org/en/download/package-manager/">透過套件管理器安裝Node.js</a> (nodejs.org)。</p> +</div> + +<h3 id="Windows_和macOS">Windows 和macOS</h3> + +<p>直接使用安裝檔吧!</p> + +<ol> + <li>下載需要的安裝檔: + <ol> + <li>開啟 <a href="https://nodejs.org/en/">https://nodejs.org/en/</a></li> + <li>對於大部分的使用者來說,直接下載LTS版本</li> + </ol> + </li> + <li>下載完成後雙擊安裝檔,並照著安裝流程繼續。</li> +</ol> + +<h3 id="Ubuntu_16.04">Ubuntu 16.04</h3> + +<p>安裝Node 8.x LTS版本最簡單的方法是使用<a href="https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions">套件管理器</a>,只要在terminal上執行兩行指令</p> + +<pre class="brush: bash notranslate"><code>curl -sL https://deb.nodesource.com/setup_8.x | sudo -E bash - +sudo apt-get install -y nodejs</code> + +</pre> + +<div class="warning"> +<p><strong>警告:</strong> 不要直接從普通的Ubuntu repositories 安裝,那邊只有很舊的版本。</p> +</div> + +<ol> +</ol> + +<h3 id="測試_Nodejs_和NPM_的安裝">測試 Nodejs 和NPM 的安裝</h3> + +<p>測試Node安裝最簡單的方法是在terminal/command上執行"version"這個指令,它會顯示當前的Node版本:</p> + +<pre class="brush: bash notranslate">>node -v +v8.9.4</pre> + +<p>NPM應該會隨著Node一起安裝,可以用相同的方法進行測試:</p> + +<pre class="brush: bash notranslate">>npm -v +5.6.0</pre> + +<p>接著用稍為令人興奮的方法來測試吧!讓我們創件一個非常基本的『純Node』伺服器,當你開啟正確的網頁時它會在瀏覽器上顯示"Hello World"</p> + +<ol> + <li>複製以下的文字到名為<strong>hellonode.js</strong>的檔案中,目前我們只用到Node而已。 + + <pre class="brush: js notranslate">//載入HTTP模組 +var http = require("http"); + +//創建HTTP 伺服器並監聽8000埠 +http.createServer(function (request, response) { + + // Set the response HTTP header with HTTP status and Content type + response.writeHead(200, {'Content-Type': 'text/plain'}); + + // Send the response body "Hello World" + response.end('Hello World\n'); +}).listen(8000); + +// Print URL for accessing server +console.log('Server running at http://127.0.0.1:8000/') +</pre> + + <p>這段程式載入『http』模組,並創建一個伺服器 (<code>createServer()</code>,並在8000埠上監聽HTTP requests。 The script then prints a message to the console about what browser URL you can use to test the server. The <code>createServer()</code> function takes as an argument a callback function that will be invoked when an HTTP request is received — this simply returns a response with an HTTP status code of 200 ("OK") and the plain text "Hello World".</p> + </li> + <li> + <div class="note"> + <p><strong>Note:</strong> Don't worry if you don't understand exactly what this code is doing yet! We'll explain our code in greater detail once we start using Express!</p> + </div> + </li> + <li>Start the server by navigating into the same directory as your <code>hellonode.js</code> file in your command prompt, and calling <code>node</code> along with the script name, like so: + <pre class="brush: bash notranslate">>node hellonode.js +Server running at http://127.0.0.1:8000/ +</pre> + </li> + <li>Navigate to the URL (<a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a>). If everything is working, the browser should simply display the string "Hello World".</li> +</ol> + +<h2 id="Using_NPM">Using NPM</h2> + +<p>Next to <em>Node</em> itself, <a href="https://docs.npmjs.com/">NPM</a> is the most important tool for working with<em> Node </em>applications. NPM is used to fetch any packages (JavaScript libraries) that an application needs for development, testing, and/or production, and may also be used to run tests and tools used in the development process. </p> + +<div class="note"> +<p><strong>Note:</strong> From Node's perspective, <em>Express</em> is just another package that you need to install using NPM and then require in your own code.</p> +</div> + +<p>You can manually use NPM to separately fetch each needed package. Typically we instead manage dependencies using a plain-text definition file named <a href="https://docs.npmjs.com/files/package.json">package.json</a>. This file lists all the dependencies for a specific JavaScript "package", including the package's name, version, description, initial file to execute, production dependencies, development dependencies, versions of <em>Node</em> it can work with, etc. The <strong>package.json</strong> file should contain everything NPM needs to fetch and run your application (if you were writing a reusable library you could use this definition to upload your package to the npm respository and make it available for other users).</p> + +<h3 id="Adding_dependencies">Adding dependencies</h3> + +<p>The following steps show how you can use NPM to download a package, save it into the project dependencies, and then require it in a Node application.</p> + +<div class="note"> +<p><strong>Note:</strong> Here we show the instructions to fetch and install the <em>Express</em> package. Later on we'll show how this package, and others, are already specified for us using the <em>Express Application Generator</em>. This section is provided because it is useful to understand how NPM works and what is being created by the application generator.</p> +</div> + +<ol> + <li>First create a directory for your new application and navigate into it: + <pre class="brush: bash notranslate">mkdir myapp +cd myapp</pre> + </li> + <li>Use the npm <code>init</code> command to create a <strong>package.json</strong> file for your application. This command prompts you for a number of things, including the name and version of your application and the name of the initial entry point file (by default this is <strong>index.js</strong>). For now, just accept the defaults: + <pre class="brush: bash notranslate">npm init</pre> + + <p>If you display the <strong>package.json</strong> file (<code>cat package.json</code>), you will see the defaults that you accepted, ending with the license.</p> + + <pre class="brush: json notranslate">{ + "name": "myapp", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC" +} +</pre> + </li> + <li>Now install the <em>Express</em> library in the <strong>myapp</strong> directory. The package will automatically be saved to the dependencies list in your <strong>package.json</strong> file. + <pre class="brush: bash notranslate">npm install express</pre> + + <p>The dependencies section of your <strong>package.json</strong> will now appear at the end of the <strong>package.json</strong> file and will include <em>Express</em>.</p> + + <pre class="brush: json notranslate">{ + "name": "myapp", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "", + "license": "ISC", +<strong> "dependencies": { + "express": "^4.16.2" + }</strong> +} +</pre> + </li> + <li>To use the library you call the <code>require()</code> function as shown below. + <pre class="notranslate"><code><strong>var express = require('express')</strong> +var app = express() + +app.get('/', function (req, res) { + res.send('Hello World!') +}) + +app.listen(</code>8000<code>, function () { + console.log('Example app listening on port </code>8000<code>!') +})</code> +</pre> + + <p>This code shows a minimal "HelloWorld" Express web application. This imports the "express" module and uses it to create a server (<code>app</code>) that listens for HTTP requests on port 8000 and prints a message to the console explaining what browser URL you can use to test the server. The <code>app.get()</code> function only responds to HTTP <code>GET</code> requests with the specified URL path ('/'), in this case by calling a function to send our <em>Hello World!</em> message. <br> + <br> + Create a file named <strong>index.js</strong> in the root of the "myapp" application directory and give it the contents shown above.</p> + </li> + <li>You can start the server by calling node with the script in your command prompt: + <pre class="brush: bash notranslate">>node index.js +Example app listening on port 8000 +</pre> + </li> + <li>Navigate to the URL (<a href="http://127.0.0.1:8000/">http://127.0.0.1:8000/</a>). If everything is working, the browser should simply display the string "Hello World!".</li> +</ol> + +<h3 id="Development_dependencies">Development dependencies</h3> + +<p>If a dependency is only used during development, you should instead save it as a "development dependency" (so that your package users don't have to install it in production). For example, to use the popular JavaScript Linting tool <a href="http://eslint.org/">eslint</a> you would call NPM as shown:</p> + +<pre class="brush: bash notranslate"><code>npm install eslint --save-dev</code></pre> + +<p>The following entry would then be added to your application's <strong>package.json</strong>:</p> + +<pre class="brush: js notranslate"> "devDependencies": { + "eslint": "^4.12.1" + } +</pre> + +<div class="note"> +<p><strong>Note:</strong> "<a href="https://en.wikipedia.org/wiki/Lint_(software)">Linters</a>" are tools that perform static analysis on software in order to recognise and report adherence/non-adherance to some set of coding best practice.</p> +</div> + +<h3 id="Running_tasks">Running tasks</h3> + +<p>In addition to defining and fetching dependencies you can also define <em>named</em> scripts in your <strong>package.json</strong> files and call NPM to execute them with the <a href="https://docs.npmjs.com/cli/run-script">run-script</a> command. This approach is commonly used to automate running tests and parts of the development or build toolchain (e.g., running tools to minify JavaScript, shrink images, LINT/analyse your code, etc).</p> + +<div class="note"> +<p><strong>Note:</strong> Task runners like <a href="http://gulpjs.com/">Gulp</a> and <a href="http://gruntjs.com/">Grunt</a> can also be used to run tests and other external tools.</p> +</div> + +<p>For example, to define a script to run the <em>eslint</em> development dependency that we specified in the previous section we might add the following script block to our <strong>package.json</strong> file (assuming that our application source is in a folder /src/js):</p> + +<pre class="brush: js notranslate">"scripts": { + ... + "lint": "eslint src/js" + ... +} +</pre> + +<p>To explain a little further, <code>eslint src/js</code> is a command that we could enter in our terminal/command line to run <code>eslint</code> on JavaScript files contained in the <code>src/js</code> directory inside our app directory. Including the above inside our app's package.json file provides a shortcut for this command — <code>lint</code>.</p> + +<p>We would then be able to run <em>eslint</em> using NPM by calling:</p> + +<pre class="brush: bash notranslate"><code>npm run-script lint +# OR (using the alias) +npm run lint</code> +</pre> + +<p>This example may not look any shorter than the original command, but you can include much bigger commands inside your npm scripts, including chains of multiple commands. You could identify a single npm script that runs all your tests at once.</p> + +<h2 id="Installing_the_Express_Application_Generator">Installing the Express Application Generator</h2> + +<p>The <a href="https://expressjs.com/en/starter/generator.html">Express Application Generator</a> tool generates an Express application "skeleton". Install the generator using NPM as shown (the <code>-g</code> flag installs the tool globally so that you can call it from anywhere):</p> + +<pre class="notranslate"><code>npm install express-generator -g</code></pre> + +<p>To create an <em>Express</em> app named "helloworld" with the default settings, navigate to where you want to create it and run the app as shown:</p> + +<pre class="brush: bash notranslate">express helloworld</pre> + +<div class="note"> +<p><strong>Note: </strong>You can also specify the template library to use and a number of other settings. Use the <code>help</code> command to see all the options:</p> + +<pre class="brush: bash notranslate">express --help +</pre> +</div> + +<p>NPM will create the new Express app in a sub folder of your current location, displaying build progress on the console. On completion, the tool will display the commands you need to enter to install the Node dependencies and start the app.</p> + +<div class="note"> +<p>The new app will have a <strong>package.json</strong> file in its root directory. You can open this to see what dependencies are installed, including Express and the template library Jade:</p> + +<pre class="brush: js notranslate">{ + "name": "helloworld", + "version": "0.0.0", + "private": true, + "scripts": { + "start": "node ./bin/www" + }, + "dependencies": { + "body-parser": "~1.18.2", + "cookie-parser": "~1.4.3", + "debug": "~2.6.9", + "express": "~4.15.5", + "jade": "~1.11.0", + "morgan": "~1.9.0", + "serve-favicon": "~2.4.5" + } +}</pre> +</div> + +<p>Install all the dependencies for the helloworld app using NPM as shown:</p> + +<pre class="brush: bash notranslate">cd helloworld +npm install +</pre> + +<p>Then run the app (the commands are slightly different for Windows and Linux/macOS), as shown below:</p> + +<pre class="brush: bash notranslate"># Run the helloworld on Windows +SET DEBUG=helloworld:* & npm start + +# Run helloworld on Linux/macOS +DEBUG=helloworld:* npm start +</pre> + +<p>The DEBUG command creates useful logging, resulting in an output like that shown below.</p> + +<pre class="brush: bash notranslate">>SET DEBUG=helloworld:* & npm start + +> helloworld@0.0.0 start D:\Github\expresstests\helloworld +> node ./bin/www + + helloworld:server Listening on port 3000 +0ms</pre> + +<p>Open a browser and navigate to <a href="http://127.0.0.1:3000/">http://127.0.0.1:3000/</a> to see the default Express welcome page.</p> + +<p><img alt="Express - Generated App Default Screen" src="https://mdn.mozillademos.org/files/14331/express_default_screen.png" style="border-style: solid; border-width: 1px; display: block; height: 301px; margin: 0px auto; width: 675px;"></p> + +<p>We'll talk more about the generated app when we get to the article on generating a skeleton application.</p> + +<ul> +</ul> + +<h2 id="總結">總結</h2> + +<p>你現在有一個 Node 開發環境在你的電腦上運行,可以用來創造 Express 網頁應用。你也看到如何用 NPM 來加載 Express到一個應用中,以及看到如何使用 Express 應用產生器,創建應用,然後執行它們。</p> + +<p>下一篇文章,我們開始跟著教程一步一步實作,使用這個開發環境與搭配工具,建立一個完整的網頁應用。</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://nodejs.org/en/download/">Downloads</a> page (nodejs.org)</li> + <li><a href="https://nodejs.org/en/download/package-manager/">Installing Node.js via package manager</a> (nodejs.org)</li> + <li><a href="http://expressjs.com/en/starter/installing.html">Installing Express</a> (expressjs.com)</li> + <li><a href="https://expressjs.com/en/starter/generator.html">Express Application Generator</a> (expressjs.com)</li> +</ul> + +<p>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Introduction", "Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs")}}</p> + + + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node introduction</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">Setting up a Node (Express) development environment</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Express Tutorial: The Local Library website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Express Tutorial Part 2: Creating a skeleton website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Express Tutorial Part 3: Using a Database (with Mongoose)</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/routes">Express Tutorial Part 4: Routes and controllers</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/deployment">Express Tutorial Part 7: Deploying to production</a></li> +</ul> diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/author_detail_page/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/author_detail_page/index.html new file mode 100644 index 0000000000..df7a5180e5 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/author_detail_page/index.html @@ -0,0 +1,89 @@ +--- +title: 作者詳情頁面 +slug: Learn/Server-side/Express_Nodejs/Displaying_data/Author_detail_page +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/Author_detail_page +--- +<p>作者細節頁面,需要呈現指定作者 <code>Author </code>的信息,使用 <code>_id</code> 欄位的值(自動產生)識別,接著是這個作者 <code>Author </code>的所有書本物件 <code>Book </code>的列表。</p> + +<h2 id="Controller_控制器">Controller 控制器</h2> + +<p>打開 <strong>/controllers/authorController.js</strong>.</p> + +<p>在檔案最上方,加入底下幾行,引入 <em>async</em> 和 <em>Book</em> 模組(作者細節頁面需要它們)。</p> + +<pre class="brush: js">var async = require('async'); +var Book = require('../models/book');</pre> + +<p>找到 exported <code>author_detail()</code> 控制器方法,並用底下代碼置換。</p> + +<pre class="brush: js">// Display detail page for a specific Author. +exports.author_detail = function(req, res, next) { + +<strong> async.parallel({ + author: function(callback) { + Author.findById(req.params.id) + .exec(callback) + }, + authors_books: function(callback) { + Book.find({ 'author': req.params.id },'title summary') + .exec(callback) + }, + }, function(err, results) { + if (err) { return next(err); } // Error in API usage. + if (results.author==null) { // No results. + var err = new Error('Author not found'); + err.status = 404; + return next(err); + } + // Successful, so render. + res.render('author_detail', { title: 'Author Detail', author: results.author, author_books: results.authors_books } ); + });</strong> + +}; +</pre> + +<p>此處的控制器方法使用<code> async.parallel()</code>,用平行的方式,查詢作者 <code>Author</code>和相應的書本實例,並附加上繪製本頁面的回調,如果 2 個要求都成功完成,就運行回調。這個方式,就跟前面的<em>種類細節頁面</em>所說明的完全相同。</p> + +<h2 id="View_視圖">View 視圖</h2> + +<p>創建 <strong>/views/author_detail.pug</strong> ,並複制貼上底下的文字。</p> + +<pre class="brush: js">extends layout + +block content + +<strong> h1 Author: #{author.name}</strong> + p #{author.date_of_birth} - #{author.date_of_death} + + div(style='margin-left:20px;margin-top:20px') + + h4 Books + + dl + each book in author_books + dt + a(href=book.url) #{book.title} + dd #{book.summary} + + else + p This author has no books. +</pre> + +<p>本模板裡的所有事物,都在先前的章節演示過了。</p> + +<h2 id="它看起來像是">它看起來像是?</h2> + +<p>運行本應用,並打開瀏覽器訪問 <a href="http://localhost:3000/">http://localhost:3000/</a>。選擇 <em>All Authors</em> 連結,然後選擇一個作者。如果每個東西都設定正確了,你的網站看起來應該會像底下的截圖。</p> + +<p><img alt="Author Detail Page - Express Local Library site" src="https://mdn.mozillademos.org/files/14466/LocalLibary_Express_Author_Detail.png" style="border-style: solid; border-width: 1px; display: block; height: 422px; margin: 0px auto; width: 1000px;"></p> + +<div class="note"> +<p><strong>注意:</strong> 作者的出生與死亡日期的外觀很醜!我們將在本文最後的自我挑戰處理它。</p> +</div> + +<h2 id="下一步">下一步</h2> + +<ul> + <li>回到 <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express 教學 5: 呈現圖書館資料</a></li> + <li>繼續教學 5 的最後一個部分: <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/BookInstance_detail_page_and_challenge">書本實例詳情頁面與自我挑戰</a></li> +</ul> diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/author_list_page/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/author_list_page/index.html new file mode 100644 index 0000000000..f207126ed1 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/author_list_page/index.html @@ -0,0 +1,85 @@ +--- +title: Author list page and Genre list page challenge +slug: Learn/Server-side/Express_Nodejs/Displaying_data/Author_list_page +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/Author_list_page +--- +<p>作者列表頁面,需要呈現數據庫中所有作者的列表,有每位作者的名字,並連結到作者詳細內容頁面。出生與死亡日期應該在名字後面,並且在同一列。</p> + +<h2 class="highlight-spanned" id="Controller_控制器"><span class="highlight-span">Controller </span>控制器</h2> + +<p>作者列表控制器函數,需要獲取所有作者實例的列表,然後將這些實例傳遞給模板進行渲染。</p> + +<p>打開 <strong>/controllers/authorController.js</strong>。在文件頂部附近,找到導出的 <code>author_list() </code>控制器方法,並將其替換為以下代碼(更改後的代碼以<strong>粗體</strong>顯示)。</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// Display list of all Authors.</span> +exports<span class="punctuation token">.</span>author_list <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span>req<span class="punctuation token">,</span> res<span class="punctuation token">,</span> next<span class="punctuation token">)</span> <span class="punctuation token">{</span> + + Author<span class="punctuation token">.</span><span class="function token">find</span><span class="punctuation token">(</span><span class="punctuation token">)</span> + <span class="punctuation token">.</span><span class="function token">sort</span><span class="punctuation token">(</span><span class="punctuation token">[</span><span class="punctuation token">[</span><span class="string token">'family_name'</span><span class="punctuation token">,</span> <span class="string token">'ascending'</span><span class="punctuation token">]</span><span class="punctuation token">]</span><span class="punctuation token">)</span> + <span class="punctuation token">.</span><span class="function token">exec</span><span class="punctuation token">(</span><span class="keyword token">function</span> <span class="punctuation token">(</span>err<span class="punctuation token">,</span> list_authors<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>err<span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="keyword token">return</span> <span class="function token">next</span><span class="punctuation token">(</span>err<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="punctuation token">}</span> + <span class="comment token">//Successful, so render</span> + res<span class="punctuation token">.</span><span class="function token">render</span><span class="punctuation token">(</span><span class="string token">'author_list'</span><span class="punctuation token">,</span> <span class="punctuation token">{</span> title<span class="punctuation token">:</span> <span class="string token">'Author List'</span><span class="punctuation token">,</span> author_list<span class="punctuation token">:</span> list_authors <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + +<span class="punctuation token">}</span><span class="punctuation token">;</span></code></pre> + +<p>The method uses the model's <code>find()</code>, <code>sort()</code> and <code>exec()</code> functions to return all <code>Author</code> objects sorted by <code>family_name</code> in alphabetic order. The callback passed to the <code>exec()</code> method is called with any errors (or <code>null</code>) as the first parameter, or a list of all authors on success. If there is an error it calls the next middleware function with the error value, and if not it renders the <strong>author_list</strong>(.pug) template, passing the page <code>title</code> and the list of authors (<code>author_list</code>).</p> + +<h2 class="highlight-spanned" id="View"><span class="highlight-span">View</span></h2> + +<p>Create <strong>/views/author_list.pug</strong> and replace its content with the text below.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">extends</span> <span class="class-name token">layout</span> + +block content + h1<span class="operator token">=</span> title + + ul + each author <span class="keyword token">in</span> author_list + li + <span class="function token">a</span><span class="punctuation token">(</span>href<span class="operator token">=</span>author<span class="punctuation token">.</span>url<span class="punctuation token">)</span> #<span class="punctuation token">{</span>author<span class="punctuation token">.</span>name<span class="punctuation token">}</span> + <span class="operator token">|</span> <span class="punctuation token">(</span>#<span class="punctuation token">{</span>author<span class="punctuation token">.</span>date_of_birth<span class="punctuation token">}</span> <span class="operator token">-</span> #<span class="punctuation token">{</span>author<span class="punctuation token">.</span>date_of_death<span class="punctuation token">}</span><span class="punctuation token">)</span> + + <span class="keyword token">else</span> + li There are no authors<span class="punctuation token">.</span></code></pre> + +<p>The view follows exactly the same pattern as our other templates.</p> + +<h2 class="highlight-spanned" id="What_does_it_look_like"><span class="highlight-span">What does it look like?</span></h2> + +<p>Run the application and open your browser to <a class="external external-icon" href="http://localhost:3000/" rel="noopener">http://localhost:3000/</a>. Then select the <em>All authors </em>link. If everything is set up correctly, the page should look something like the following screenshot.</p> + +<p><img alt="Author List Page - Express Local Library site" src="https://mdn.mozillademos.org/files/14468/LocalLibary_Express_Author_List.png" style="display: block; height: 453px; margin: 0px auto; width: 1200px;"></p> + +<div class="note"> +<p><strong>Note:</strong> The appearance of the author <em>lifespan </em>dates is ugly! You can improve this using the <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data#date_formatting">same approach</a> as we used for the <code>BookInstance</code> list (adding the virtual property for the lifespan to the <code>Author</code> model). This time, however, there are missing dates, and references to nonexistent properties are ignored unless strict mode is in effect. <code>moment()</code> returns the current time, and you don't want missing dates to be formatted as if they were today. One way to deal with this is to define the body of the function that returns a formatted date so it returns a blank string unless the date actually exists. For example:</p> + +<p><code>return this.date_of_birth ? moment(this.date_of_birth).format('YYYY-MM-DD') : '';</code></p> +</div> + +<h2 id="Genre_list_page—challenge!Edit">Genre list page—challenge!<a class="button section-edit only-icon" href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data$edit#Genre_list_page—challenge!" rel="nofollow, noindex"><span>Edit</span></a></h2> + +<p>In this section you should implement your own genre list page. The page should display a list of all genres in the database, with each genre linked to its associated detail page. A screenshot of the expected result is shown below.</p> + +<p><img alt="Genre List - Express Local Library site" src="https://mdn.mozillademos.org/files/14460/LocalLibary_Express_Genre_List.png" style="border-style: solid; border-width: 1px; display: block; height: 346px; margin: 0px auto; width: 600px;"></p> + +<p>The genre list controller function needs to get a list of all <code>Genre</code> instances, and then pass these to the template for rendering.</p> + +<ol> + <li>You will need to edit <code>genre_list()</code> in <strong>/controllers/genreController.js</strong>. </li> + <li>The implementation is almost exactly the same as the <code>author_list()</code> controller. + <ul> + <li>Sort the results by name, in ascending order.</li> + </ul> + </li> + <li>The template to be rendered should be named <strong>genre_list.pug</strong>.</li> + <li>The template to be rendered should be passed the variables <code>title</code> ('Genre List') and <code>genre_list</code> (the list of genres returned from your <code>Genre.find()</code> callback.</li> + <li>The view should match the screenshot/requirements above (this should have a very similar structure/format to the Author list view, except for the fact that genres do not have dates).</li> +</ol> + +<h2 id="Next_steps">Next steps</h2> + +<p>Return to <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a>.</p> + +<p>Proceed to the next subarticle of part 5: <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Genre_detail_page">Genre detail page</a>.</p> diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/book_detail_page/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/book_detail_page/index.html new file mode 100644 index 0000000000..31f3d65284 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/book_detail_page/index.html @@ -0,0 +1,112 @@ +--- +title: 書本詳情頁面 +slug: Learn/Server-side/Express_Nodejs/Displaying_data/Book_detail_page +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/Book_detail_page +--- +<p><em>書本細節頁面</em>需要呈現一本指定書本(<code>Book</code>)的信息, 使用它的 <code>_id</code> 字段值(自動產生)做為識別,接著是圖書館中書本實例(<code>BookInstance</code>)的信息。無論我們在哪裡呈現一個作者、種類、或書本實例,都應該連結到它的細節頁面。</p> + +<h2 id="Controller_控制器">Controller 控制器</h2> + +<p>打開 <strong>/controllers/bookController.js.</strong> ,找到 exported <code>book_detail()</code> 控制器方法,用底下的代碼置換。</p> + +<pre class="brush: js">// Display detail page for a specific book. +exports.book_detail = function(req, res, next) { + +<strong> async.parallel({ + book: function(callback) { + + Book.findById(req.params.id) + .populate('author') + .populate('genre') + .exec(callback); + }, + book_instance: function(callback) { + + BookInstance.find({ 'book': req.params.id }) + .exec(callback); + }, + }, function(err, results) { + if (err) { return next(err); } + if (results.book==null) { // No results. + var err = new Error('Book not found'); + err.status = 404; + return next(err); + } + // Successful, so render. + res.render('book_detail', { title: 'Title', book: results.book, book_instances: results.book_instance } ); + });</strong> + +}; + +</pre> + +<div class="note"> +<p><strong>注意:</strong> 我們不需要用 require 導入 <em>async</em> 和 <em>BookInstance</em>,當我們實作主頁面控制器的時候,我們就已經引入這些模組。</p> +</div> + +<p>此處的控制器方法使用 <code>async.parallel()</code>,用平行的方式找到 <code>Book</code> 以及它的相應複本 (<code>BookInstances</code>) 。這樣的處理方式,就跟上面的 <em>種類細節頁面</em> 所說明的完全相同。</p> + +<h2 id="View_視圖">View 視圖</h2> + +<p>創建 <strong>/views/book_detail.pug </strong>並加入底下文字。</p> + +<pre class="brush: js">extends layout + +block content + h1 #{title}: #{book.title} + + p #[strong Author:] + a(href=book.author.url) #{book.author.name} + p #[strong Summary:] #{book.summary} + p #[strong ISBN:] #{book.isbn} + p #[strong Genre:]&nbsp; + each val, index in book.genre + a(href=val.url) #{val.name} + if index < book.genre.length - 1 + |, + + div(style='margin-left:20px;margin-top:20px') + h4 Copies + + each val in book_instances + hr + if val.status=='Available' + <strong>p.text-success</strong> #{val.status} + else if val.status=='Maintenance' + p.text-danger #{val.status} + else + p.text-warning #{val.status} + p #[strong Imprint:] #{val.imprint} + if val.status!='Available' + p #[strong Due back:] #{val.due_back} + p #[strong Id:]&nbsp; + a(href=val.url) #{val._id} + + else + p There are no copies of this book in the library. +</pre> + +<p>在這個模板裡,幾乎每個東西都在先前的章節演示過了。</p> + +<div class="note"> +<p><strong>注意:</strong> 與該書相關的種類列表,在模板中的實作,如以下代碼。除了最後一本書之外,在與本書相關的每個種類之後,都會添加一個逗號。</p> + +<pre> p #[strong Genre:] + each val, index in book.genre + a(href=val.url) #{val.name} + if index < book.genre.length - 1 + |, </pre> +</div> + +<h2 id="它看起來像是">它看起來像是?</h2> + +<p>運行本應用,並打開瀏覽器訪問 <a href="http://localhost:3000/">http://localhost:3000/</a>。選擇 <em>All books</em> 連結,然後選擇其中一本書。如果每個東西都設定正確了,你的頁面看起來應該像是底下的截圖。</p> + +<p><img alt="Book Detail Page - Express Local Library site" src="https://mdn.mozillademos.org/files/14470/LocalLibary_Express_Book_Detail.png" style="border-style: solid; border-width: 1px; display: block; height: 616px; margin: 0px auto; width: 1200px;"></p> + +<h2 id="下一步">下一步</h2> + +<ul> + <li>回到 <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express 教學 5: 呈現圖書館資料</a></li> + <li>繼續教學 5 下一個部分: <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Author_detail_page">作者詳情頁面</a></li> +</ul> diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/book_list_page/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/book_list_page/index.html new file mode 100644 index 0000000000..a35b31767d --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/book_list_page/index.html @@ -0,0 +1,72 @@ +--- +title: 書本清單頁面 +slug: Learn/Server-side/Express_Nodejs/Displaying_data/Book_list_page +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/Book_list_page +--- +<p>接下做我們將實作書本列表頁面。這個頁面需要呈現數據庫中所有書本的列表,包含每本書的作者、標題,標題將成為一個超連結,連到書本詳細內容頁面。</p> + +<h2 class="highlight-spanned" id="控制器">控制器</h2> + +<p>書本列表控制器函數,需要獲取數據庫中所有 <code>Book</code>對象的列表,然後將這些對像傳給模板進行呈現。</p> + +<p>打開 <strong>/controllers/bookController.js</strong>. 找到導出的 <code>book_list()</code>控制器方法,並替換為下面的代碼。</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// Display list of all Books.</span> +exports<span class="punctuation token">.</span>book_list <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span>req<span class="punctuation token">,</span> res<span class="punctuation token">,</span> next<span class="punctuation token">)</span> <span class="punctuation token">{</span> + + Book<span class="punctuation token">.</span><span class="function token">find</span><span class="punctuation token">(</span><span class="punctuation token">{</span><span class="punctuation token">}</span><span class="punctuation token">,</span> <span class="string token">'title author'</span><span class="punctuation token">)</span> + <span class="punctuation token">.</span><span class="function token">populate</span><span class="punctuation token">(</span><span class="string token">'author'</span><span class="punctuation token">)</span> + <span class="punctuation token">.</span><span class="function token">exec</span><span class="punctuation token">(</span><span class="keyword token">function</span> <span class="punctuation token">(</span>err<span class="punctuation token">,</span> list_books<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>err<span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="keyword token">return</span> <span class="function token">next</span><span class="punctuation token">(</span>err<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="punctuation token">}</span> + <span class="comment token">//Successful, so render</span> + res<span class="punctuation token">.</span><span class="function token">render</span><span class="punctuation token">(</span><span class="string token">'book_list'</span><span class="punctuation token">,</span> <span class="punctuation token">{</span> title<span class="punctuation token">:</span> <span class="string token">'Book List'</span><span class="punctuation token">,</span> book_list<span class="punctuation token">:</span> list_books <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + +<span class="punctuation token">}</span><span class="punctuation token">;</span></code></pre> + +<p>該方法使用模型的<code>find()</code>函數,返回所有 <code>Book </code>對象,選擇僅返回標題 <code>title </code>和作者 <code>author</code>,因為我們不需要其他字段(它也會返回 <code>_id </code>和虛擬欄位字段)。這裡我們還調用 <code>Book </code>上的 <code>populate()</code>,指定作者 <code>author</code>欄位字段 — 這將用完整的作者信息,替換儲存的書本作者 id。</p> + +<p>成功時,傳遞給查詢的回調,將呈現 <strong>book_list</strong>(.pug) 模板,將標題 <code>title </code>和<code>book_list</code>(包含作者的書本列表)作為變量傳遞。</p> + +<h2 class="highlight-spanned" id="View視圖"><span class="highlight-span">View</span>視圖</h2> + +<p>創建<strong> /views/book_list.pug</strong> 並複制底下的文字。</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">extends</span> <span class="class-name token">layout</span> + +block content + h1<span class="operator token">=</span> title + + ul + each book <span class="keyword token">in</span> book_list + li + <span class="function token">a</span><span class="punctuation token">(</span>href<span class="operator token">=</span>book<span class="punctuation token">.</span>url<span class="punctuation token">)</span> #<span class="punctuation token">{</span>book<span class="punctuation token">.</span>title<span class="punctuation token">}</span> + <span class="operator token">|</span> <span class="punctuation token">(</span>#<span class="punctuation token">{</span>book<span class="punctuation token">.</span>author<span class="punctuation token">.</span>name<span class="punctuation token">}</span><span class="punctuation token">)</span> + + <span class="keyword token">else</span> + li There are no books<span class="punctuation token">.</span></code></pre> + +<p>這個視圖擴展了<strong> layout.pug</strong> 基本模板,並覆蓋了名為 '<strong>content</strong>' 的 <code>block </code>區塊 。它顯示我們從控制器傳入的標題 <code>title</code>(通過 <code>render()</code>方法),然後使用 <code>each</code>-<code>in</code>-<code>else </code>語法,遍歷 <code>book_list</code>變量。為每本圖書創建一個列表項,以顯示書名,並作為書的詳細信息頁面的鏈接,後面跟著作者姓名。如果 <code>book_list</code>中沒有書,則執行 <code>else</code> 子句,並顯示文字 “沒有書本” 'There are no books'。</p> + +<p> </p> + +<div class="note"> +<p><strong>注意:</strong> 我們使用 <code>book.url</code>,為每本書提供詳細記錄鏈接(我們已經實現了此路由,但尚未實現此頁面)。這是 <code>Book</code> 模型的一個虛擬屬性,它使用模型實例的 <code>_id</code> 字段,生成唯一的 URL 路徑。</p> +</div> + +<p>在這裡,我們感興趣的是,每本書被定義為兩行,第二行使用管道(上面高亮顯示)。這種方法是必要的,因為如果作者姓名位於上一行,那麼它將成為超鏈接的一部分。</p> + +<h2 class="highlight-spanned" id="它看起來像是">它看起來像是?</h2> + +<p>運行本應用 (參見 <a href="/zh-TW/docs/Learn/Server-side/Express_Nodejs/routes#Testing_the_routes">測試路由</a> 有相關的命令) ,並打開你的瀏覽器,訪問 <a class="external external-icon" href="http://localhost:3000/" rel="noopener">http://localhost:3000/</a>。然後選擇所有書本連結 <em>All books</em>。如果每樣東西都設定正確了,你的網站看起來應該像底下的截圖。</p> + +<p> </p> + +<p><img alt="Book List Page - Express Local Library site" src="https://mdn.mozillademos.org/files/14464/LocalLibary_Express_Book_List.png" style="border-style: solid; border-width: 1px; display: block; height: 387px; margin: 0px auto; width: 918px;"></p> + +<h2 id="下一步">下一步</h2> + +<ul> + <li>回到 <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express 教學 5: 呈現圖書館資料</a></li> + <li>繼續教學 5 下個部分: <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/BookInstance_list_page">書本實例清單頁面</a></li> +</ul> diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/bookinstance_detail_page_and_challenge/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/bookinstance_detail_page_and_challenge/index.html new file mode 100644 index 0000000000..e04981411c --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/bookinstance_detail_page_and_challenge/index.html @@ -0,0 +1,91 @@ +--- +title: 書本實例詳情頁面與自我挑戰 +slug: >- + Learn/Server-side/Express_Nodejs/Displaying_data/BookInstance_detail_page_and_challenge +translation_of: >- + Learn/Server-side/Express_Nodejs/Displaying_data/BookInstance_detail_page_and_challenge +--- +<h2 id="書本實例詳情頁面">書本實例詳情頁面</h2> + +<p><code>BookInstance</code> 詳情頁面,需要呈現每一個 <code>BookInstance </code>的信息,用 <code>_id</code> 欄位字段值(自動產生)做識別。它包含了 <code>Book</code> 名稱 (也是一個連結,連到 <em>書本細節</em>頁面),接著是紀錄中的其它的信息。</p> + +<h3 id="Controller_控制器">Controller 控制器</h3> + +<p>打開 <strong>/controllers/bookinstanceController.js</strong>. 找到 exported <code>bookinstance_detail()</code> 控制器方法,並用底下代碼置換。</p> + +<pre class="brush: js">// Display detail page for a specific BookInstance. +exports.bookinstance_detail = function(req, res, next) { + +<strong> BookInstance.findById(req.params.id) + .populate('book') + .exec(function (err, bookinstance) { + if (err) { return next(err); } + if (bookinstance==null) { // No results. + var err = new Error('Book copy not found'); + err.status = 404; + return next(err); + } + // Successful, so render. + res.render('bookinstance_detail', { title: 'Book:', bookinstance: bookinstance}); + })</strong> + +}; +</pre> + +<p>該方法使用從 URL(使用路由)中提取的特定書本實例的ID,調用<code>BookInstance.findById()</code>,並通過請求參數(<code style="font-style: normal; font-weight: normal;">req.params.id</code>),在控制器中訪問。然後調用<code>populate()</code>來獲取相關 <code>Book </code>的詳細信息。</p> + +<h3 id="View_視圖">View 視圖</h3> + +<p>創建 <strong>/views/bookinstance_detail.pug</strong> ,並複製下面的內容。</p> + +<pre class="brush: js">extends layout + +block content + +<strong> h1 ID: #{bookinstance._id}</strong> + + p #[strong Title:] + a(href=bookinstance.book.url) #{bookinstance.book.title} + p #[strong Imprint:] #{bookinstance.imprint} + + p #[strong Status:] + if bookinstance.status=='Available' + span.text-success #{bookinstance.status} + else if bookinstance.status=='Maintenance' + span.text-danger #{bookinstance.status} + else + span.text-warning #{bookinstance.status} + + if bookinstance.status!='Available' + p #[strong Due back:] #{bookinstance.due_back} +</pre> + +<p>本模組中的所有東西,都在先前的章節演示過了。</p> + +<h3 id="它看起來像是">它看起來像是?</h3> + +<p>運行本應用,並打開瀏覽器訪問 <a href="http://localhost:3000/">http://localhost:3000/</a>/。選擇 <em>All book-instances</em> 連結,然後選擇其中一本。如果每個東西都設定正確了,你的網站看起來應該像是底下的截圖。</p> + +<p><img alt="BookInstance Detail Page - Express Local Library site" src="https://mdn.mozillademos.org/files/14472/LocalLibary_Express_BookInstance_Detail.png" style="border-style: solid; border-width: 1px; display: block; height: 362px; margin: 0px auto; width: 1000px;"></p> + +<h2 id="自我挑戰">自我挑戰</h2> + +<p>目前,我們網站上顯示的大多數日期,都使用默認的 JavaScript 格式(例如 <em>Tue Dec 06 2016 15:49:58 GMT+1100 </em>(AUS東部夏令時間))。本文的挑戰,是改善作者<code>Author</code>生命週期日期顯示的外觀信息(死亡/誔生日期)和<em>BookInstance詳細信息</em>頁面,使用格式:December 6th, 2016。</p> + +<div class="note"> +<p><strong>注意:</strong> 您可以使用與我們用於 <em>Book Instance List</em> 的相同方法(將生命週期的虛擬屬性,添加到<code>Author</code>模型,並使用 <a href="https://www.npmjs.com/package/moment">moment </a>來設置日期字符串的格式)。</p> +</div> + +<p>這個挑戰的要求: </p> + +<ol> + <li>用 BookInstance 詳細信息頁面中的 <code>due_back_formatted</code> 替換 <code>due_back</code>。</li> + <li>更新作者模塊以添加壽命虛擬屬性。壽命應該有兩個值: <em>date_of_birth - date_of_death</em>,這兩個值的格式與 <code>BookInstance.due_back_formatted</code>的日期格式相同。</li> + <li>在當前使用 <code>date_of_birth</code> 和 <code>date_of_death</code>的所有視圖中,使用 <code>Author.lifespan</code> 。</li> +</ol> + +<h2 id="下一步">下一步</h2> + +<ul> + <li>回到 <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express 教學 5: 呈現圖書館資料</a></li> +</ul> diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/bookinstance_list_page/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/bookinstance_list_page/index.html new file mode 100644 index 0000000000..1b1656258e --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/bookinstance_list_page/index.html @@ -0,0 +1,71 @@ +--- +title: 書本實例清單頁面 +slug: Learn/Server-side/Express_Nodejs/Displaying_data/BookInstance_list_page +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/BookInstance_list_page +--- +<p>接下來,我們將實作圖書館中所有書本實例 (<code>BookInstance</code>) 的列表頁面。這個頁面需要包含與每個 <code>BookInstance</code> (鏈接到其詳細信息頁面) 關聯的書本 <code>Book</code> 標題,以及 <code>BookInstance</code>模型中的其他信息,包含每個副本的狀態,印記和唯一ID。唯一ID的文字,應該鏈接到 <code>BookInstance</code> 詳細信息頁面。</p> + +<h2 class="highlight-spanned" id="Controller_控制器"><span class="highlight-span">Controller</span> 控制器</h2> + +<p><code>BookInstance</code>列表控制器函數,需要獲取所有書本實例的列表,填充關聯的書本信息,然後將列表傳遞給模板以進行呈現。</p> + +<p>打開 <strong>/controllers/bookinstanceController.js</strong>。找到導出的 <code>bookinstance_list()</code>控制器方法,並用以下代碼替換它(更改後的代碼以<strong>粗體</strong>顯示)。</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// Display list of all BookInstances.</span> +exports<span class="punctuation token">.</span>bookinstance_list <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span>req<span class="punctuation token">,</span> res<span class="punctuation token">,</span> next<span class="punctuation token">)</span> <span class="punctuation token">{</span> + + BookInstance<span class="punctuation token">.</span><span class="function token">find</span><span class="punctuation token">(</span><span class="punctuation token">)</span> + <span class="punctuation token">.</span><span class="function token">populate</span><span class="punctuation token">(</span><span class="string token">'book'</span><span class="punctuation token">)</span> + <span class="punctuation token">.</span><span class="function token">exec</span><span class="punctuation token">(</span><span class="keyword token">function</span> <span class="punctuation token">(</span>err<span class="punctuation token">,</span> list_bookinstances<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>err<span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="keyword token">return</span> <span class="function token">next</span><span class="punctuation token">(</span>err<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="punctuation token">}</span> + <span class="comment token">// Successful, so render</span> + res<span class="punctuation token">.</span><span class="function token">render</span><span class="punctuation token">(</span><span class="string token">'bookinstance_list'</span><span class="punctuation token">,</span> <span class="punctuation token">{</span> title<span class="punctuation token">:</span> <span class="string token">'Book Instance List'</span><span class="punctuation token">,</span> bookinstance_list<span class="punctuation token">:</span> list_bookinstances <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + +<span class="punctuation token">}</span><span class="punctuation token">;</span></code></pre> + +<p>此方法使用模型的<code>find()</code>函數,返回所有 <code>BookInstance</code>對象。然後它將一個調用,以菊花鏈方式連接到 <code>populate()</code>,附加書本 <code>book</code>欄位字段,這將使用完整的 <code>Book</code>文檔,替換每個 <code>BookInstance</code>儲存的書本 ID。</p> + +<p>成功時,傳遞給查詢的回調,會呈現 <strong>bookinstance_list</strong> (.pug)模板,並將標題<code>title</code>和書籍實例列表 <code>bookinstance_list</code>作為變量傳遞。</p> + +<h2 class="highlight-spanned" id="View_視圖"><span class="highlight-span">View</span> 視圖</h2> + +<p>創建 <strong>/views/bookinstance_list.pug </strong>,並複制貼上底下的文字。</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">extends</span> <span class="class-name token">layout</span> + +block content + h1<span class="operator token">=</span> title + + ul + each val <span class="keyword token">in</span> bookinstance_list + li + <span class="function token">a</span><span class="punctuation token">(</span>href<span class="operator token">=</span>val<span class="punctuation token">.</span>url<span class="punctuation token">)</span> #<span class="punctuation token">{</span>val<span class="punctuation token">.</span>book<span class="punctuation token">.</span>title<span class="punctuation token">}</span> <span class="punctuation token">:</span> #<span class="punctuation token">{</span>val<span class="punctuation token">.</span>imprint<span class="punctuation token">}</span> <span class="operator token">-</span> + <span class="keyword token">if</span> val<span class="punctuation token">.</span>status<span class="operator token">==</span><span class="string token">'Available'</span> + span<span class="punctuation token">.</span>text<span class="operator token">-</span>success #<span class="punctuation token">{</span>val<span class="punctuation token">.</span>status<span class="punctuation token">}</span> + <span class="keyword token">else</span> <span class="keyword token">if</span> val<span class="punctuation token">.</span>status<span class="operator token">==</span><span class="string token">'Maintenance'</span> + span<span class="punctuation token">.</span>text<span class="operator token">-</span>danger #<span class="punctuation token">{</span>val<span class="punctuation token">.</span>status<span class="punctuation token">}</span> + <span class="keyword token">else</span> + span<span class="punctuation token">.</span>text<span class="operator token">-</span>warning #<span class="punctuation token">{</span>val<span class="punctuation token">.</span>status<span class="punctuation token">}</span> + <span class="keyword token">if</span> val<span class="punctuation token">.</span>status<span class="operator token">!=</span><span class="string token">'Available'</span> + span <span class="function token"> </span><span class="punctuation token">(</span>Due<span class="punctuation token">:</span> #<span class="punctuation token">{</span>val<span class="punctuation token">.</span>due_back<span class="punctuation token">}</span> <span class="punctuation token">)</span> + + <span class="keyword token">else</span> + li There are no book copies <span class="keyword token">in</span> <span class="keyword token">this</span> library<span class="punctuation token">.</span></code></pre> + +<p>這個視圖與其他視圖非常相似。它擴展了佈局,替換內容區塊,顯示從控制器傳入的標題 <code>title</code>,並遍歷 <code>bookinstance_list</code> 中的所有書籍副本。對於每個副本,我們都會顯示它的狀態(用顏色編碼),如果書本不可用,則顯示其預期返回日期。這裡引入了一個新功能 — 我們可以在標籤之後使用點符號表示法,來指定一個類別。因此,<code>span.text-success </code>將被編譯為 <<code>span class="text-success"</code>> (也可以用 Pug 編寫為 <code>span(class="text-success"</code>)。</p> + +<p> </p> + +<h2 class="highlight-spanned" id="它看起來像是">它看起來像是?</h2> + +<p>運行本應用,打開瀏覽器訪問 <a class="external external-icon" href="http://localhost:3000/" rel="noopener">http://localhost:3000/</a>,然後選擇 All book-instances 連結。假如每個東西都設定正確了,你的網站看起來應該像是底下的截圖。</p> + +<p><img alt="BookInstance List Page - Express Local Library site" src="https://mdn.mozillademos.org/files/14474/LocalLibary_Express_BookInstance_List.png" style="border-style: solid; border-width: 1px; display: block; height: 322px; margin: 0px auto; width: 1200px;"></p> + +<h2 id="下一步">下一步</h2> + +<ul> + <li>回到 <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express 教學 5: 呈現圖書館資料</a></li> + <li>繼續教學 5下一個部分: <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Date_formatting_using_moment">格式化日期 - 使用 moment</a>.</li> +</ul> diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/date_formatting_using_moment/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/date_formatting_using_moment/index.html new file mode 100644 index 0000000000..ecd3ee7f0d --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/date_formatting_using_moment/index.html @@ -0,0 +1,60 @@ +--- +title: 使用 moment 做日期格式化 +slug: Learn/Server-side/Express_Nodejs/Displaying_data/Date_formatting_using_moment +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/Date_formatting_using_moment +--- +<p>我們模型的日期預設呈現很難看: <em>Tue Dec 06 2016 15:49:58 GMT+1100 (AUS Eastern Daylight Time)</em>。在本節中,我們將展示如何更新上一節中的 <em>書本實例 BookInstance 列表頁面</em>,以更友好的格式顯示<code>due_date</code>欄位字段:December 6th, 2016。</p> + +<p>我們將使用的方法,是在我們的<code>BookInstance</code>模型中,創建一個返回格式化日期的虛擬屬性。我們將使用 <a class="external external-icon" href="https://www.npmjs.com/package/moment" rel="noopener">moment</a> 來做實際的格式化,這是一個輕量級 JavaScript日期庫,用於解析,驗證,操作和格式化日期。</p> + +<div class="note"> +<p><strong>注意:</strong> 我們可以直接在 Pug 模板中,使用 moment 格式化字符串,或者可以在許多其它地方格式化字符串。使用虛擬屬性,可以使我們獲得格式化的日期,這與我們當前獲取 <code>due_date</code> 的方式完全相同。</p> +</div> + +<h2 class="highlight-spanned" id="安裝_moment"><span class="highlight-span">安裝 moment</span></h2> + +<p>在項目的根目錄,輸入下列命令</p> + +<p> </p> + +<pre class="brush: bash line-numbers language-bash"><code class="language-bash">npm install moment</code></pre> + +<h2 class="highlight-spanned" id="創建虛擬屬性">創建虛擬屬性</h2> + +<ol> + <li>打開 <strong>./models/bookinstance.js</strong>.</li> + <li>在此頁面最上方,引入 <em>moment</em>. + <pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">var</span> moment <span class="operator token">=</span> <span class="function token">require</span><span class="punctuation token">(</span><span class="string token">'moment'</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + </li> +</ol> + +<p>在 url 屬性後面,加入虛擬屬性 <code>due_back_formatted</code> 。</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">BookInstanceSchema +<span class="punctuation token">.</span><span class="function token">virtual</span><span class="punctuation token">(</span><span class="string token">'due_back_formatted'</span><span class="punctuation token">)</span> +<span class="punctuation token">.</span><span class="keyword token">get</span><span class="punctuation token">(</span><span class="keyword token">function</span> <span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">return</span> <span class="function token">moment</span><span class="punctuation token">(</span><span class="keyword token">this</span><span class="punctuation token">.</span>due_back<span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">format</span><span class="punctuation token">(</span><span class="string token">'MMMM Do, YYYY'</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<div class="note"> +<p><strong>注意:</strong> 格式化方法可以使用幾乎任何模式顯示日期。 <a class="external external-icon" href="http://momentjs.com/docs/#/displaying/" rel="noopener">moment</a>文檔中,可以找到表示不同日期組件的語法。</p> +</div> + +<h2 class="highlight-spanned" id="更新視圖">更新視圖</h2> + +<p>打開 <strong>/views/bookinstance_list.pug</strong> ,然後用 <code>due_back_formatted</code> 取代 <code>due_back</code> 。</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"> <span class="keyword token">if</span> val<span class="punctuation token">.</span>status<span class="operator token">!=</span><span class="string token">'Available'</span> + <span class="comment token">//span (Due: #{val.due_back} )</span> + span <span class="function token"> </span><span class="punctuation token">(</span>Due<span class="punctuation token">:</span> #<span class="punctuation token">{</span>val<span class="punctuation token">.</span>due_back_formatted<span class="punctuation token">}</span> <span class="punctuation token">)</span> </code></pre> + +<p>這就是本章節的全部了。如果你訪問側邊欄的 <em>All book-instances</em> ,你應該會看到所有的歸還日期都更吸引人了!</p> + +<h2 id="下一步">下一步</h2> + +<ul> + <li>回到 <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express 教學 5: 呈現圖書館資料</a></li> + <li>繼續教學 5 的下一個部分: <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Author_list_page">Author list page and Genre list page challenge</a>.</li> +</ul> + +<p> </p> diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/flow_control_using_async/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/flow_control_using_async/index.html new file mode 100644 index 0000000000..5271bd6722 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/flow_control_using_async/index.html @@ -0,0 +1,137 @@ +--- +title: 使用 async 進行非同步流控制 +slug: Learn/Server-side/Express_Nodejs/Displaying_data/flow_control_using_async +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/flow_control_using_async +--- +<p>有些<em>本地圖書館</em>網頁的控制器代碼,會依賴多重非同步要求的結果,可能會需要以某種特定次序運行,或者以平行方式運行。為了管理流控制,並在我們所有需要用到的信息,都已經可以取用的時候,再繪製網頁,我們將使用許多人採用的 node <a class="external external-icon" href="https://www.npmjs.com/package/async" rel="noopener">async</a> 模組。</p> + +<div class="note"> +<p><strong>注意:</strong> 在 JavaScript 中有許多其他方法,可以管理異步行為和流控制,包括相對較新的 JavaScript 語言功能,如 <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/Techniques/Promises">Promises</a>。</p> +</div> + +<p>Async 有很多有用的方法(請查看<a href="http://caolan.github.io/async/docs.html">文檔</a>)。一些最重要的功能是:</p> + +<p> </p> + +<ul> + <li><code><a class="external external-icon" href="http://caolan.github.io/async/docs.html#parallel" rel="noopener">async.parallel()</a></code> 執行必須並行執行的任何操作。</li> + <li><code><a class="external external-icon" href="http://caolan.github.io/async/docs.html#series" rel="noopener">async.series()</a></code> 用於當需要確保異步操作是序列執行的。</li> + <li><code><a class="external external-icon" href="http://caolan.github.io/async/docs.html#waterfall" rel="noopener">async.waterfall()</a></code> 用於必須序列運行的操作,每個操作取決於前面操作的結果。</li> +</ul> + +<h2 class="highlight-spanned" id="為什麼需要這麼做">為什麼需要這麼做?</h2> + +<p>我們在 <em>Express</em> 中使用的大多數方法,都是異步的 - 您指定要執行的操作,傳遞回調。該方法立即返回,並在請求的操作完成時,調用回調。按照 <em>Express</em> 中的慣例,回調函數將<em>錯誤值</em>作為第一個參數傳遞(或成功時為 <code>null</code>),並將函數的結果(如果有的話)作為第二個參數傳遞。</p> + +<p>如果控制器只需要<em>執行<strong>一個</strong>異步操作</em>,來獲取呈現頁面所需的信息,那麼實現很簡單 - 我們只需在回調中呈現模板。下面的代碼片段,顯示了一個函數,該函數呈現模型 <code>SomeModel</code> 的計數(使用Mongoose <code><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#model_Model.count" rel="noopener">count()</a></code>方法):</p> + +<pre class="brush: js"><code>exports.some_model_count = function(req, res, next) { + +</code> SomeModel.count({ a_model_field: 'match_value' }, function (err, count) { + // ... do something if there is an err + + // On success, render the result by passing count into the render function (here, as the variable 'data'). + res.render('the_template', { data: count } ); + }); +<code>}</code> +</pre> + +<p>但是,如果您需要進行<strong>多個</strong>異步查詢,並且在完成所有操作之前,無法呈現頁面,該怎麼辦?一個單純的實現可以用 “菊花鏈” 連接請求,在先前請求的回調中,啟動後續請求,並在最終回調中呈現響應。這種方法的問題,是我們的請求必須串行運行,即使並行運行它們可能更有效。這也可能導致複雜的嵌套代碼,通常稱為<a href="http://callbackhell.com/">回調地獄</a>。</p> + +<p>一個更好的解決方案,是並行執行所有請求,然後在所有查詢完成後執行單個回調。這是 <em>Async</em> 模塊簡化的流操作!</p> + +<h2 class="highlight-spanned" id="Asynchronous_operations_in_parallel"><span class="highlight-span">Asynchronous operations in parallel</span></h2> + +<p>The method <code><a class="external external-icon" href="http://caolan.github.io/async/docs.html#parallel" rel="noopener">async.parallel()</a></code> is used to run multiple asynchronous operations in parallel.</p> + +<p>The first argument to <code>async.parallel()</code> is a collection of the asynchronous functions to run (an array, object or other iterable). Each function is passed a <code>callback(err, result)</code> which it must call on completion with an error <code>err</code> (which can be <code>null</code>) and an optional <code>results</code> value.</p> + +<p>The optional second argument to <code>async.parallel()</code> is a callback that will be run when all the functions in the first argument have completed. The callback is invoked with an error argument and a result collection that contains the results of the individual asynchronous operations. The result collection is of the same type as the first argument (i.e. if you pass an array of asynchronous functions, the final callback will be invoked with an array of results). If any of the parallel functions reports an error the callback is invoked early (with the error value).</p> + +<p>The example below shows how this works when we pass an object as the first argument. As you can see, the results are <em>returned</em> in an object with the same property names as the original functions that were passed in.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">async</span><span class="punctuation token">.</span><span class="function token">parallel</span><span class="punctuation token">(</span><span class="punctuation token">{</span> + one<span class="punctuation token">:</span> <span class="keyword token">function</span><span class="punctuation token">(</span>callback<span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="punctuation token">.</span><span class="punctuation token">.</span><span class="punctuation token">.</span> <span class="punctuation token">}</span><span class="punctuation token">,</span> + two<span class="punctuation token">:</span> <span class="keyword token">function</span><span class="punctuation token">(</span>callback<span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="punctuation token">.</span><span class="punctuation token">.</span><span class="punctuation token">.</span> <span class="punctuation token">}</span><span class="punctuation token">,</span> + <span class="punctuation token">.</span><span class="punctuation token">.</span><span class="punctuation token">.</span> + something_else<span class="punctuation token">:</span> <span class="keyword token">function</span><span class="punctuation token">(</span>callback<span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="punctuation token">.</span><span class="punctuation token">.</span><span class="punctuation token">.</span> <span class="punctuation token">}</span> + <span class="punctuation token">}</span><span class="punctuation token">,</span> + <span class="comment token">// optional callback</span> + <span class="keyword token">function</span><span class="punctuation token">(</span>err<span class="punctuation token">,</span> results<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// 'results' is now equal to: {one: 1, two: 2, ..., something_else: some_value}</span> + <span class="punctuation token">}</span> +<span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<p>If you instead pass an array of functions as the first argument, the results will be an array (the array order results will match the original order that the functions were declared—not the order in which they completed).</p> + +<h2 class="highlight-spanned" id="Asynchronous_operations_in_series"><span class="highlight-span">Asynchronous operations in series</span></h2> + +<p>The method <code><a class="external external-icon" href="http://caolan.github.io/async/docs.html#series" rel="noopener">async.series()</a></code> is used to run multiple asynchronous operations in sequence, when subsequent functions do not depend on the output of earlier functions. It is essentially declared and behaves in the same way as <code>async.parallel()</code>.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">async</span><span class="punctuation token">.</span><span class="function token">series</span><span class="punctuation token">(</span><span class="punctuation token">{</span> + one<span class="punctuation token">:</span> <span class="keyword token">function</span><span class="punctuation token">(</span>callback<span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="punctuation token">.</span><span class="punctuation token">.</span><span class="punctuation token">.</span> <span class="punctuation token">}</span><span class="punctuation token">,</span> + two<span class="punctuation token">:</span> <span class="keyword token">function</span><span class="punctuation token">(</span>callback<span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="punctuation token">.</span><span class="punctuation token">.</span><span class="punctuation token">.</span> <span class="punctuation token">}</span><span class="punctuation token">,</span> + <span class="punctuation token">.</span><span class="punctuation token">.</span><span class="punctuation token">.</span> + something_else<span class="punctuation token">:</span> <span class="keyword token">function</span><span class="punctuation token">(</span>callback<span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="punctuation token">.</span><span class="punctuation token">.</span><span class="punctuation token">.</span> <span class="punctuation token">}</span> + <span class="punctuation token">}</span><span class="punctuation token">,</span> + <span class="comment token">// optional callback after the last asynchronous function completes.</span> + <span class="keyword token">function</span><span class="punctuation token">(</span>err<span class="punctuation token">,</span> results<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// 'results' is now equals to: {one: 1, two: 2, ..., something_else: some_value} </span> + <span class="punctuation token">}</span> +<span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<div class="note"> +<p><strong>Note:</strong> The ECMAScript (JavaScript) language specification states that the order of enumeration of an object is undefined, so it is possible that the functions will not be called in the same order as you specify them on all platforms. If the order really is important, then you should pass an array instead of an object, as shown below.</p> +</div> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">async</span><span class="punctuation token">.</span><span class="function token">series</span><span class="punctuation token">(</span><span class="punctuation token">[</span> + <span class="keyword token">function</span><span class="punctuation token">(</span>callback<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// do some stuff ...</span> + <span class="function token">callback</span><span class="punctuation token">(</span><span class="keyword token">null</span><span class="punctuation token">,</span> <span class="string token">'one'</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span><span class="punctuation token">,</span> + <span class="keyword token">function</span><span class="punctuation token">(</span>callback<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// do some more stuff ... </span> + <span class="function token">callback</span><span class="punctuation token">(</span><span class="keyword token">null</span><span class="punctuation token">,</span> <span class="string token">'two'</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + <span class="punctuation token">]</span><span class="punctuation token">,</span> + <span class="comment token">// optional callback</span> + <span class="keyword token">function</span><span class="punctuation token">(</span>err<span class="punctuation token">,</span> results<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// results is now equal to ['one', 'two'] </span> + <span class="punctuation token">}</span> +<span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<h2 class="highlight-spanned" id="Dependent_asynchronous_operations_in_series"><span class="highlight-span">Dependent asynchronous operations in series</span></h2> + +<p>The method <code><a class="external external-icon" href="http://caolan.github.io/async/docs.html#waterfall" rel="noopener">async.waterfall()</a></code> is used to run multiple asynchronous operations in sequence when each operation is dependent on the result of the previous operation.</p> + +<p>The callback invoked by each asynchronous function contains <code>null</code> for the first argument and results in subsequent arguments. Each function in the series takes the results arguments of the previous callback as the first parameters, and then a callback function. When all operations are complete, a final callback is invoked with the result of the last operation. The way this works is more clear when you consider the code fragment below (this example is from the <em>async</em> documentation):</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">async</span><span class="punctuation token">.</span><span class="function token">waterfall</span><span class="punctuation token">(</span><span class="punctuation token">[</span> + <span class="keyword token">function</span><span class="punctuation token">(</span>callback<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="function token">callback</span><span class="punctuation token">(</span><span class="keyword token">null</span><span class="punctuation token">,</span> <span class="string token">'one'</span><span class="punctuation token">,</span> <span class="string token">'two'</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span><span class="punctuation token">,</span> + <span class="keyword token">function</span><span class="punctuation token">(</span>arg1<span class="punctuation token">,</span> arg2<span class="punctuation token">,</span> callback<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// arg1 now equals 'one' and arg2 now equals 'two' </span> + <span class="function token">callback</span><span class="punctuation token">(</span><span class="keyword token">null</span><span class="punctuation token">,</span> <span class="string token">'three'</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span><span class="punctuation token">,</span> + <span class="keyword token">function</span><span class="punctuation token">(</span>arg1<span class="punctuation token">,</span> callback<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// arg1 now equals 'three'</span> + <span class="function token">callback</span><span class="punctuation token">(</span><span class="keyword token">null</span><span class="punctuation token">,</span> <span class="string token">'done'</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> +<span class="punctuation token">]</span><span class="punctuation token">,</span> <span class="keyword token">function</span> <span class="punctuation token">(</span>err<span class="punctuation token">,</span> result<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// result now equals 'done'</span> +<span class="punctuation token">}</span> +<span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<h2 class="highlight-spanned" id="Installing_async"><span class="highlight-span">Installing async</span></h2> + +<p>Install the async module using the NPM package manager so that we can use it in our code. You do this in the usual way, by opening a prompt in the root of the <em>LocalLibrary</em> project and enter the following command:</p> + +<pre class="brush: bash line-numbers language-bash"><code class="language-bash">npm install async</code></pre> + +<h2 id="Next_steps">Next steps</h2> + +<ul> + <li>Return to <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a>.</li> + <li>Proceed to the next subarticle of Part 5: <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Template_primer">Template primer</a>.</li> +</ul> diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/genre_detail_page/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/genre_detail_page/index.html new file mode 100644 index 0000000000..2c7f1e938b --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/genre_detail_page/index.html @@ -0,0 +1,123 @@ +--- +title: Genre detail page +slug: Learn/Server-side/Express_Nodejs/Displaying_data/Genre_detail_page +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/Genre_detail_page +--- +<p>種類<em>細節</em>頁面,需要利用<code>_id</code> 字段值 (自動生成) ,以呈現特定種類實例的信息。此頁面應該呈現種類名稱,各個種類的所有書本列表(每本書都連結到書本的細節頁面)。</p> + +<p> </p> + +<h2 id="Controller_控制器">Controller 控制器</h2> + +<p>打開 <strong>/controllers/genreController.js</strong> ,並在檔案最上方引用 <em>async</em> 和 <em>Book</em> 模組。</p> + +<pre class="brush: js">var Book = require('../models/book'); +var async = require('async'); +</pre> + +<p>Find the exported <code>genre_detail</code><code>()</code> controller method and replace it with the following code.</p> + +<pre class="brush: js">// Display detail page for a specific Genre. +exports.genre_detail = function(req, res, next) { + +<strong> async.parallel({ + genre: function(callback) { + Genre.findById(req.params.id) + .exec(callback); + }, + + genre_books: function(callback) { + Book.find({ 'genre': req.params.id }) + .exec(callback); + }, + + }, function(err, results) { + if (err) { return next(err); } + if (results.genre==null) { // No results. + var err = new Error('Genre not found'); + err.status = 404; + return next(err); + } + // Successful, so render + res.render('genre_detail', { title: 'Genre Detail', genre: results.genre, genre_books: results.genre_books } ); + });</strong> + +}; +</pre> + +<p>The method uses <code>async.parallel()</code> to query the genre name and its associated books in parallel, with the callback rendering the page when (if) both requests complete successfully.</p> + +<p>The ID of the required genre record is encoded at the end of the URL and extracted automatically based on the route definition (<strong>/genre/:id</strong>). The ID is accessed within the controller via the request parameters: <code style="font-style: normal; font-weight: normal;">req.params.id</code>. It is used in <code style="font-style: normal; font-weight: normal;">Genre.findById()</code> to get the current genre. It is also used to get all <code>Book</code> objects that have the genre ID in their <code>genre</code> field: <code>Book.find({ 'genre': req.params.id })</code>.</p> + +<div class="note"> +<p><strong>Note:</strong> If the genre does not exist in the database (i.e. it may have been deleted) then <code>findById()</code> will return successfully with no results. In this case we want to display a "not found" page, so we create an <code>Error</code> object and pass it to the <code>next</code> middleware function in the chain. </p> + +<pre class="brush: js"><strong>if (results.genre==null) { // No results. + var err = new Error('Genre not found'); + err.status = 404; + return next(err); +}</strong> +</pre> + +<p>The message will then propagate through to our error handling code (this was set up when we <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website#error_handling">generated the app skeleton</a> - for more information see <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction#Handling_errors">Handling Errors</a>).</p> +</div> + +<p>The rendered view is <strong>genre_detail</strong> and it is passed variables for the <code>title</code>, <code>genre</code> and the list of books in this genre (<code>genre_books</code>).</p> + +<h2 id="View">View</h2> + +<p>Create <strong>/views/genre_detail.pug</strong> and fill it with the text below:</p> + +<pre class="brush: js">extends layout + +block content + + <strong>h1 Genre: #{genre.name}</strong> + + div(style='margin-left:20px;margin-top:20px') + + h4 Books + + dl + each book in genre_books + dt + a(href=book.url) #{book.title} + dd #{book.summary} + + else + p This genre has no books +</pre> + +<p>The view is very similar to all our other templates. The main difference is that we don't use the <code>title</code> passed in for the first heading (though it is used in the underlying <strong>layout.pug</strong> template to set the page title).</p> + +<h2 id="What_does_it_look_like">What does it look like?</h2> + +<p>Run the application and open your browser to <a href="http://localhost:3000/">http://localhost:3000/</a>. Select the <em>All genres</em> link, then select one of the genres (e.g. "Fantasy"). If everything is set up correctly, your page should look something like the following screenshot.</p> + +<p><img alt="Genre Detail Page - Express Local Library site" src="https://mdn.mozillademos.org/files/14462/LocalLibary_Express_Genre_Detail.png" style="border-style: solid; border-width: 1px; display: block; height: 523px; margin: 0px auto; width: 1000px;"></p> + +<div class="note"> +<p>You might get an error similar to this:</p> + +<pre class="brush: bash">Cast to ObjectId failed for value " 59347139895ea23f9430ecbb" at path "_id" for model "Genre" +</pre> + +<p>This is a mongoose error coming from the <strong>req.params.id</strong>. To solve this problem, first you need to require mongoose on the <strong>genreController.js</strong> page like this:</p> + +<pre class="brush: js"> var mongoose = require('mongoose'); +</pre> + +<p>Then use <strong>mongoose.Types.ObjectId() </strong>to convert the id to a that can be used. For example:</p> + +<pre class="brush: js">exports.genre_detail = function(req, res, next) { + var id = mongoose.Types.ObjectId(req.params.id); + ... +</pre> +</div> + +<h2 id="Next_steps">Next steps</h2> + +<ul> + <li>Return to <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a>.</li> + <li>Proceed to the next subarticle of part 5: <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Book_detail_page">Book detail page</a>.</li> +</ul> diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/home_page/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/home_page/index.html new file mode 100644 index 0000000000..8adc4b11f9 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/home_page/index.html @@ -0,0 +1,133 @@ +--- +title: 主頁 +slug: Learn/Server-side/Express_Nodejs/Displaying_data/Home_page +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/Home_page +--- +<p>我們創建的第一個頁面,是網站的主頁面,可以從網站的根目錄 (<code>'/'</code>) ,或者 catalog 的根目錄 (<code>catalog/</code>) 訪問。這將呈現一些網站的靜態文字描述,以及動態計算數據庫中不同記錄類型的“計數”。</p> + +<p>我們已經為主頁創建了一個路由。為了完成頁面,我們需要更新控制器函數,以從數據庫中提取記錄的“計數”,並創建一個可用於呈現頁面的視圖(模板)。</p> + +<h2 id="路由">路由</h2> + +<p>在<a href="/zh-TW/docs/Learn/Server-side/Express_Nodejs/routes">前面的教程</a>,我們創建 index 頁面路由。此處要提醒的是,所有的路由函式,都定義在<strong> /routes/catalog.js</strong>:</p> + +<pre class="brush: js ">// GET catalog home page. +router.get('/', book_controller.index); //This actually maps to /catalog/ because we import the route with a /catalog prefix</pre> + +<p>Where the callback function parameter (<code>book_controller.index</code>) is defined in <strong>/controllers/bookController.js</strong>:</p> + +<pre class="brush: js">exports.index = function(req, res, next) { + res.send('NOT IMPLEMENTED: Site Home Page'); +}</pre> + +<p>It is this controller function that we extend to get information from our models and then render it using a template (view).</p> + +<h2 id="Controller">Controller</h2> + +<p>The index controller function needs to fetch information about how many <code>Book</code>, <code>BookInstance</code>, available <code>BookInstance</code>, <code>Author</code>, and <code>Genre</code> records we have in the database, render this data in a template to create an HTML page, and then return it in an HTTP response.</p> + +<div class="note"> +<p><strong>Note:</strong> We use the <code><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#model_Model.countDocuments" rel="noopener">countDocuments()</a></code> method to get the number of instances of each model. This is called on a model with an optional set of conditions to match against in the first argument and a callback in the second argument (as discussed in <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Using a Database (with Mongoose)</a>, and you can also return a <code>Query</code> and then execute it with a callback later. The callback will be returned when the database returns the count, with an error value (or <code>null</code>) as the first parameter and the count of records (or null if there was an error) as the second parameter.</p> + +<pre class="brush: js ">SomeModel.countDocuments({ a_model_field: 'match_value' }, function (err, count) { + // ... do something if there is an err + // ... do something with the count if there was no error + });</pre> +</div> + +<p>Open <strong>/controllers/bookController.js</strong>. Near the top of the file you should see the exported <code>index()</code> function.</p> + +<pre class="brush: python ">var Book = require('../models/book') + +exports.index = function(req, res, next) { + res.send('NOT IMPLEMENTED: Site Home Page'); +}</pre> + +<p>Replace all the code above with the following code fragment. The first thing this does is import (<code>require()</code>) all the models (highlighted in bold). We need to do this because we'll be using them to get our counts of records. It then imports the <em>async</em> module.</p> + +<pre class="brush: js ">var Book = require('../models/book'); +var Author = require('../models/author'); +var Genre = require('../models/genre'); +var BookInstance = require('../models/bookinstance'); + +var async = require('async'); + +exports.index = function(req, res) { + + async.parallel({ + book_count: function(callback) { + Book.countDocuments({}, callback); // Pass an empty object as match condition to find all documents of this collection + }, + book_instance_count: function(callback) { + BookInstance.countDocuments({}, callback); + }, + book_instance_available_count: function(callback) { + BookInstance.countDocuments({status:'Available'}, callback); + }, + author_count: function(callback) { + Author.countDocuments({}, callback); + }, + genre_count: function(callback) { + Genre.countDocuments({}, callback); + }, + }, function(err, results) { + res.render('index', { title: 'Local Library Home', error: err, data: results }); + }); +};</pre> + +<p>The <code>async.parallel()</code> method is passed an object with functions for getting the counts for each of our models. These functions are all started at the same time. When all of them have completed the final callback is invoked with the counts in the results parameter (or an error).</p> + +<p>On success the callback function calls <code><a class="external external-icon" href="http://expressjs.com/en/4x/api.html#res.render" rel="noopener">res.render()</a></code>, specifying a view (template) named '<strong>index</strong>' and an object containing the data that is to be inserted into it (this includes the results object that contains our model counts). The data is supplied as key-value pairs, and can be accessed in the template using the key.</p> + +<div class="note"> +<p><strong>Note:</strong> The callback function from <code>async.parallel()</code> above is a little unusual in that we render the page whether or not there was an error (normally you might use a separate execution path for handling the display of errors).</p> +</div> + +<h2 id="View">View</h2> + +<p>Open <strong>/views/index.pug</strong> and replace its content with the text below.</p> + +<pre class="brush: js ">extends layout + +block content + h1= title + p Welcome to #[em LocalLibrary], a very basic Express website developed as a tutorial example on the Mozilla Developer Network. + + h1 Dynamic content + + if error + p Error getting dynamic content. + else + p The library has the following record counts: + + ul + li #[strong Books:] !{data.book_count} + li #[strong Copies:] !{data.book_instance_count} + li #[strong Copies available:] !{data.book_instance_available_count} + li #[strong Authors:] !{data.author_count} + li #[strong Genres:] !{data.genre_count}</pre> + +<p>The view is straightforward. We extend the <strong>layout.pug</strong> base template, overriding the <code>block</code> named '<strong>content</strong>'. The first <code>h1</code> heading will be the escaped text for the <code>title</code> variable that was passed into the <code>render()</code> function—note the use of the '<code>h1=</code>' so that the following text is treated as a JavaScript expression. We then include a paragraph introducing the LocalLibrary.</p> + +<p>Under the <em>Dynamic content</em> heading we check whether the error variable passed in from the <code>render()</code> function has been defined. If so, we note the error. If not, we get and list the number of copies of each model from the <code>data</code> variable.</p> + +<div class="note"> +<p><strong>Note:</strong> We didn't escape the count values (i.e. we used the <code>!{}</code> syntax) because the count values are calculated. If the information was supplied by end-users then we'd escape the variable for display.</p> +</div> + +<h2 id="What_does_it_look_like">What does it look like?</h2> + +<p>At this point we should have created everything needed to display the index page. Run the application and open your browser to <a class="external external-icon" href="http://localhost:3000/" rel="noopener">http://localhost:3000/</a>. If everything is set up correctly, your site should look something like the following screenshot.</p> + +<p><img alt="Home page - Express Local Library site" src="https://mdn.mozillademos.org/files/14458/LocalLibary_Express_Home.png" style="display: block; height: 440px; margin: 0px auto; width: 1000px;"></p> + +<div class="note"> +<p><strong>Note:</strong> You won't be able to use the sidebar links yet because the urls, views, and templates for those pages haven't been defined. If you try you'll get errors like "NOT IMPLEMENTED: Book list" for example, depending on the link you click on. These string literals (which will be replaced with proper data) were specified in the different controllers that live inside your "controllers" file.</p> +</div> + +<h2 id="Next_steps">Next steps</h2> + +<ul> + <li>Return to <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a>.</li> + <li>Proceed to the next subarticle of part 5: <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Book_list_page">Book list page</a>.</li> +</ul> diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/index.html new file mode 100644 index 0000000000..2073a02bc8 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/index.html @@ -0,0 +1,87 @@ +--- +title: 'Express 教程 5: 呈現圖書館數據' +slug: Learn/Server-side/Express_Nodejs/Displaying_data +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/routes", "Learn/Server-side/Express_Nodejs/forms", "Learn/Server-side/Express_Nodejs")}}</div> + +<p class="summary">我們現在準備好要新增網頁,以顯示本地圖書館網站的書本與其它資料。這些網頁將包括一個主頁 ,顯示我們每個模型的型態有多少筆紀錄,以及我們所有模型的清單與細節頁面。藉此,我們將得到從數據庫取得紀錄、以及使用樣版的實務經驗。</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">前置條件:</th> + <td>完成先前教程主題 (包含 Express 教程 4: 路由與控制器)。</td> + </tr> + <tr> + <th scope="row">目標:</th> + <td>了解如何使用非同步模組與 Pug 樣版語言,以及如何從我們的控制器函式中的 URL 得取資料。</td> + </tr> + </tbody> +</table> + +<h2 id="概覽">概覽</h2> + +<p>在我們先前的教程中,定義了可以用來跟資料庫互動的 <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Mongoose models</a> ,並創建了一些初始的圖書館紀錄。我們接著<a href="/zh-TW/docs/Learn/Server-side/Express_Nodejs/routes">創建本地圖書館網站需要的所有路由</a>,但僅使用"空殼控制器" 函式(這些是骨架控制器函式,當一個網頁被存取時,只回傳一個"未實作" 信息)。</p> + +<p>下一步,是為這些顯示圖書館信息的網頁,提供充分的實作(我們將在後面的文章,檢視網頁表單的實作,像是創建、更新、刪除信息)。這包含了更新控制器函式,以利用我們的模型取得紀錄,並定義模板,為使用者顯示這些信息。</p> + +<p>我們在一開始,提供概略的總覽/重點主題,解釋在控制器函式中,如何管理非同步操作,以及如何使用 Pug 撰寫模板。然後我們將為每一個主要的 "唯讀" 網頁提供實作步驟,並且在使用到任何特別的、或新的特性時,會附上簡短的解釋說明。</p> + +<p>本教程的最後,你對路由、非同步函式、視圖、模型如何實際運作,應該有了更好的理解。</p> + +<h2 id="本教程的章節">本教程的章節</h2> + +<p>本教程分為下列章節,說明為了顯示圖書館網站頁面,如何新增各種特性 。在進入下一個教程之前,你需要閱讀並逐一實作下列章節。</p> + +<ol> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/flow_control_using_async">使用 async 控制非同步流</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Template_primer">模板入門</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/LocalLibrary_base_template">本地圖書館基礎模板</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Home_page">主頁</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Book_list_page">書本清單頁面</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/BookInstance_list_page">書本實例清單頁面</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Date_formatting_using_moment">日期格式化 - 使用 moment</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Author_list_page">作者清單頁面、分類清單頁面、與自我挑戰</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Genre_detail_page">分類詳情頁面</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Book_detail_page">書本詳情頁面</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Author_detail_page">作者詳情頁面</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/BookInstance_detail_page_and_challenge">書本實例詳情頁面與自我挑戰</a></li> +</ol> + +<h2 id="總結">總結</h2> + +<p>我們現在已經為我們的網站,創建了所有 "唯讀" 的頁面: 一個主頁,可以顯示每一個模組的實例數量,書本的列表與詳細信息頁面,書本的實例、作者、分類。沿著目前的學習路徑,我們學到了許多基本知識,有控制器、在非同步作業時管理流控制、使用 Pug 創建視圖、使用模型查詢數據庫、如何從視圖傳送信息到模板、如何創建並擴展模板。而完成挑戰的人,還會學到如何用 moment 處理日期。</p> + +<p>在下一篇文章,我們將依據目前為止學到的知識,創建HTML 表單以及表單管理代碼,開始修改儲存在網站中的資料。</p> + +<h2 id="參閱">參閱</h2> + +<ul> + <li><a href="http://caolan.github.io/async/docs.html">Async module</a> (Async docs)</li> + <li><a href="https://expressjs.com/en/guide/using-template-engines.html">Using Template engines with Express</a> (Express docs)</li> + <li><a href="https://pugjs.org/api/getting-started.html">Pug</a> (Pug docs)</li> + <li><a href="http://momentjs.com/docs/">Moment</a> (Moment docs)</li> +</ul> + +<p>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/routes", "Learn/Server-side/Express_Nodejs/forms", "Learn/Server-side/Express_Nodejs")}}</p> + +<p> </p> + +<h2 id="本教學連結">本教學連結</h2> + +<ul> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node introduction</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">Setting up a Node (Express) development environment</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Express Tutorial: The Local Library website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Express Tutorial Part 2: Creating a skeleton website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Express Tutorial Part 3: Using a Database (with Mongoose)</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/routes">Express Tutorial Part 4: Routes and controllers</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/deployment">Express Tutorial Part 7: Deploying to production</a></li> +</ul> + +<p> </p> diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/locallibrary_base_template/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/locallibrary_base_template/index.html new file mode 100644 index 0000000000..c67e82f07e --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/locallibrary_base_template/index.html @@ -0,0 +1,71 @@ +--- +title: 本地圖書館基礎模板 +slug: Learn/Server-side/Express_Nodejs/Displaying_data/LocalLibrary_base_template +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/LocalLibrary_base_template +--- +<p> </p> + +<p>現在我們了解如何使用 Pug 拓展模板,讓我們開始項目,創建一個基礎模板。這個模板會有一個側邊欄,連結到本教程中將要創建的各個頁面(例如,呈現並創建書本、種類、作者等等),以及一個主要內容區域,我們將在每個頁面中進行覆寫。</p> + +<p>開啟 <strong>/views/layout.pug </strong>,並以下列代碼,置換其內容。</p> + +<pre class="brush: html line-numbers language-html"><code class="language-html">doctype html +html(lang='en') + head + title= title + meta(charset='utf-8') + meta(name='viewport', content='width=device-width, initial-scale=1') + link(rel='stylesheet', href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css') + script(src='https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js') + script(src='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js') + link(rel='stylesheet', href='/stylesheets/style.css') + body + div(class='container-fluid') + div(class='row') + div(class='col-sm-2') + block sidebar + ul(class='sidebar-nav') + li + a(href='/catalog') Home + li + a(href='/catalog/books') All books + li + a(href='/catalog/authors') All authors + li + a(href='/catalog/genres') All genres + li + a(href='/catalog/bookinstances') All book-instances + li + hr + li + a(href='/catalog/author/create') Create new author + li + a(href='/catalog/genre/create') Create new genre + li + a(href='/catalog/book/create') Create new book + li + a(href='/catalog/bookinstance/create') Create new book instance (copy) + + div(class='col-sm-10') + block content</code></pre> + +<p>此模板使用(並包含)來自 <a class="external external-icon" href="http://getbootstrap.com/" rel="noopener">Bootstrap</a> 的 JavaScript 和 CSS ,以改進 HTML 頁面的佈局和呈現方式。使用 Bootstrap 或其它客戶端網頁框架,是一種快速的方式,可以創建吸引人的網頁,能夠良好地適應不同的瀏覽器尺寸,並且允許我們處理頁面的呈現,而不需要糾纒於任何不同尺寸的細節—此處我們只想專注於伺服端代碼!</p> + +<p>佈局的安排應該相當明白,假如你已經閱讀了之前的 <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data#Template_primer">模板入門</a>。注意,使用 <code>block content</code> 當做定位符號,放到頁面內容將要放置的地方。</p> + +<p>基礎模板也參考了一個本地 css 檔 (<strong>style.css</strong>) ,此檔提供了一些額外的樣式。打開 <strong>/public/stylesheets/style.css</strong> ,並用底下的 CSS 代碼,取代它的內容:</p> + +<pre class="brush: css line-numbers language-css"><code class="language-css"><span class="selector token"><span class="class token">.sidebar-nav</span> </span><span class="punctuation token">{</span> + <span class="property token">margin-top</span><span class="punctuation token">:</span> <span class="number token">20</span>px<span class="punctuation token">;</span> + <span class="property token">padding</span><span class="punctuation token">:</span> <span class="number token">0</span><span class="punctuation token">;</span> + <span class="property token">list-style</span><span class="punctuation token">:</span> none<span class="punctuation token">;</span> +<span class="punctuation token">}</span></code></pre> + +<p>當我們開始運行網站時,我們應該看到側邊欄出現!在本教程的下個部分,我們將使用以上的佈局,來定義各個頁面。</p> + +<h2 id="下一步">下一步</h2> + +<ul> + <li>回到 <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a>.</li> + <li>繼續教學 5 下個章節: <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/Home_page">Home page</a>.</li> +</ul> diff --git a/files/zh-tw/learn/server-side/express_nodejs/displaying_data/template_primer/index.html b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/template_primer/index.html new file mode 100644 index 0000000000..af976b7155 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/displaying_data/template_primer/index.html @@ -0,0 +1,149 @@ +--- +title: 模板入門 +slug: Learn/Server-side/Express_Nodejs/Displaying_data/Template_primer +translation_of: Learn/Server-side/Express_Nodejs/Displaying_data/Template_primer +--- +<p>模板是一個文字檔,定義了一個輸出檔的<em>結構</em>或者排版,使用定位符號表示,當模板被繪製時,資料將插入到何處(在<em>Express</em>,模板被稱為<em>視圖</em>)。</p> + +<h2 id="Express_模板選擇">Express 模板選擇</h2> + +<p>Express 可以與許多不同的<a href="https://expressjs.com/zh-tw/guide/using-template-engines.html">模板渲染引擎</a>一起使用。在本教程中,我們使用 <a class="external external-icon" href="https://pugjs.org/api/getting-started.html" rel="noopener">Pug</a>(以前稱為 <em>Jade</em>)作為模板。這是最流行的 Node 模板語言,並且官方將自身描述為 “用於編寫 HTML,語法乾淨且空格敏感,受 <a class="external external-icon" href="http://haml.info/" rel="noopener">Haml </a>影響很大”。</p> + +<p>不同的模板語言使用不同的方法,來定義佈局和標記數據的佔位符 — 一些使用 HTML 來定義佈局,而另一些則使用可以編譯為 HTML 的不同標記格式。 Pug 是第二種類型;它使用 HTML 的<em>表示形式</em>,其中任何行中的第一個單詞,通常表示HTML元素,後續行中的縮進,用於表示嵌套在這些元素中的任何內容。結果是一個頁面定義直接轉換為 HTML,但可以說更簡潔,更容易閱讀。</p> + +<div class="note"> +<p><strong>Note:</strong> The downside of using <em>Pug</em> is that it is sensitive to indentation and whitespace (if you add an extra space in the wrong place you may get an unhelpful error code). However once you have your templates in place, they are very easy to read and maintain.</p> +</div> + +<h2 class="highlight-spanned" id="Template_configuration"><span class="highlight-span">Template configuration</span></h2> + +<p>The <em>LocalLibrary</em> was configured to use <a class="external external-icon" href="https://pugjs.org/api/getting-started.html" rel="noopener">Pug</a> when we <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">created the skeleton website</a>. You should see the pug module included as a dependency in the website's <strong>package.json</strong> file, and the following configuration settings in the <strong>app.js</strong> file. The settings tell us that we're using pug as the view engine, and that <em>Express</em> should search for templates in the <strong>/views</strong> subdirectory.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// View engine setup.</span> +app<span class="punctuation token">.</span><span class="keyword token">set</span><span class="punctuation token">(</span><span class="string token">'views'</span><span class="punctuation token">,</span> path<span class="punctuation token">.</span><span class="function token">join</span><span class="punctuation token">(</span>__dirname<span class="punctuation token">,</span> <span class="string token">'views'</span><span class="punctuation token">)</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +app<span class="punctuation token">.</span><span class="keyword token">set</span><span class="punctuation token">(</span><span class="string token">'view engine'</span><span class="punctuation token">,</span> <span class="string token">'pug'</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<p>If you look in the views directory you will see the .pug files for the project's default views. These include the view for the home page (<strong>index.pug</strong>) and base template (<strong>layout.pug</strong>) that we will need to replace with our own content.</p> + +<pre><code>/express-locallibrary-tutorial //the project root + /views + error.pug + <strong>index.pug</strong> + layout.pug</code> +</pre> + +<h2 class="highlight-spanned" id="Template_syntax"><span class="highlight-span">Template syntax</span></h2> + +<p>The example template file below shows off many of Pug's most useful features.</p> + +<p>The first thing to notice is that the file maps the structure of a typical HTML file, with the first word in (almost) every line being an HTML element, and indentation being used to indicate nested elements. So for example, the <code>body</code> element is inside an <code>html</code> element, and paragraph elements (<code>p</code>) are within the <code>body</code> element, etc. Non-nested elements (e.g. individual paragraphs) are on separate lines.</p> + +<pre class="brush: html line-numbers language-html"><code class="language-html">doctype html +html(lang="en") + head + title= title + script(type='text/javascript'). + body + h1= title + + p This is a line with #[em some emphasis] and #[strong strong text] markup. + p This line has un-escaped data: !{'<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>em</span><span class="punctuation token">></span></span> is emphasised<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>em</span><span class="punctuation token">></span></span>'} and escaped data: #{'<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>em</span><span class="punctuation token">></span></span> is not emphasised<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>em</span><span class="punctuation token">></span></span>'}. + | This line follows on. + p= 'Evaluated and <span class="tag token"><span class="tag token"><span class="punctuation token"><</span>em</span><span class="punctuation token">></span></span>escaped expression<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>em</span><span class="punctuation token">></span></span>:' + title + + <span class="comment token"><!-- You can add HTML comments directly --></span> + // You can add single line JavaScript comments and they are generated to HTML comments + //- Introducing a single line JavaScript comment with "//-" ensures the comment isn't rendered to HTML + + p A line with a link + a(href='/catalog/authors') Some link text + | and some extra text. + + #container.col + if title + p A variable named "title" exists. + else + p A variable named "title" does not exist. + p. + Pug is a terse and simple template language with a + strong focus on performance and powerful features. + + h2 Generate a list + + ul + each val in [1, 2, 3, 4, 5] + li= val</code></pre> + +<p>Element attributes are defined in parentheses after their associated element. Inside the parentheses, the attributes are defined in comma- or whitespace- separated lists of the pairs of attribute names and attribute values, for example:</p> + +<ul> + <li><code>script(type='text/javascript')</code>, <code>link(rel='stylesheet', href='/stylesheets/style.css')</code></li> + <li><code>meta(name='viewport' content='width=device-width initial-scale=1')</code></li> +</ul> + +<p>The values of all attributes are <em>escaped</em> (e.g. characters like "<code>></code>" are converted to their HTML code equivalents like "<code>&gt;"</code>) to prevent injection of JavaScript/cross-site scripting attacks.</p> + +<p>If a tag is followed by the equals sign, the following text is treated as a JavaScript <em>expression</em>. So for example, in the first line below, the content of the <code>h1</code> tag will be <em>variable</em> <code>title</code> (either defined in the file or passed into the template from Express). In the second line the paragraph content is a text string concatented with the <code>title</code> variable. In both cases the default behaviour is to <em>escape</em> the line.</p> + +<pre class="brush: html line-numbers language-html"><code class="language-html">h1= title +p= 'Evaluated and <span class="tag token"><span class="tag token"><span class="punctuation token"><</span>em</span><span class="punctuation token">></span></span>escaped expression<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>em</span><span class="punctuation token">></span></span>:' + title</code></pre> + +<p>If there is no equals symbol after the tag then the content is treated as plain text. Within the plain text you can insert escaped and unescaped data using the <code>#{}</code> and<code> !{}</code> syntax, as shown below. You can also add raw HTML within the plain text.</p> + +<pre class="brush: html line-numbers language-html"><code class="language-html">p This is a line with #[em some emphasis] and #[strong strong text] markup. +p This line has an un-escaped string: !{'<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>em</span><span class="punctuation token">></span></span> is emphasised<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>em</span><span class="punctuation token">></span></span>'}, an escaped string: #{'<span class="tag token"><span class="tag token"><span class="punctuation token"><</span>em</span><span class="punctuation token">></span></span> is not emphasised<span class="tag token"><span class="tag token"><span class="punctuation token"></</span>em</span><span class="punctuation token">></span></span>'}, and escaped variables: #{title}.</code></pre> + +<div class="note"> +<p><strong>Tip:</strong> You will almost always want to escape data from users (via the <strong><code>#{}</code></strong> syntax). Data that can be trusted (e.g. generated counts of records, etc.) may be displayed without escaping the values.</p> +</div> + +<p>You can use the pipe ('<strong>|</strong>') character at the beginning of a line to indicate "<a class="external external-icon" href="https://pugjs.org/language/plain-text.html" rel="noopener">plain text</a>". For example, the additional text shown below will be displayed on the same line as the preceding anchor, but will not be linked.</p> + +<pre class="brush: html line-numbers language-html"><code class="language-html">a(href='http://someurl/') Link text +| Plain text</code></pre> + +<p>Pug allows you to perform conditional operations using <code>if</code>, <code>else</code> , <code>else if</code> and <code>unless</code>—for example:</p> + +<pre class="brush: html line-numbers language-html"><code class="language-html">if title + p A variable named "title" exists +else + p A variable named "title" does not exist</code></pre> + +<p>You can also perform loop/iteration operations using <code>each-in</code> or <code>while</code> syntax. In the code fragment below we've looped through an array to display a list of variables (note the use of the 'li=' to evaluate the "val" as a variable below. The value you iterate across can also be passed into the template as a variable!</p> + +<pre class="brush: html line-numbers language-html"><code class="language-html">ul + each val in [1, 2, 3, 4, 5] + li= val</code></pre> + +<p>The syntax also supports comments (that can be rendered in the output—or not—as you choose), mixins to create reusable blocks of code, case statements, and many other features. For more detailed information see <a class="external external-icon" href="https://pugjs.org/api/getting-started.html" rel="noopener">The Pug docs</a>.</p> + +<h2 class="highlight-spanned" id="Extending_templates"><span class="highlight-span">Extending templates</span></h2> + +<p>Across a site, it is usual for all pages to have a common structure, including standard HTML markup for the head, footer, navigation, etc. Rather than forcing developers to duplicate this "boilerplate" in every page, <em>Pug</em> allows you to declare a base template and then extend it, replacing just the bits that are different for each specific page.</p> + +<p>For example, the base template <strong>layout.pug</strong> created in our <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">skeleton project</a> looks like this:</p> + +<pre class="brush: html line-numbers language-html"><code class="language-html">doctype html +html + head + title= title + link(rel='stylesheet', href='/stylesheets/style.css') + body + block content</code></pre> + +<p>The <code>block</code> tag is used to mark up sections of content that may be replaced in a derived template (if the block is not redefined then its implementation in the base class is used).</p> + +<p>The default <strong>index.pug</strong> (created for our skeleton project) shows how we override the base template. The <code>extends</code> tag identifies the base template to use, and then we use <code>block <em>section_name</em></code> to indicate the new content of the section that we will override.</p> + +<pre class="brush: html line-numbers language-html"><code class="language-html">extends layout + +block content + h1= title + p Welcome to #{title}</code></pre> + +<h2 id="Next_steps">Next steps</h2> + +<ul> + <li>Return to <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a>.</li> + <li>Proceed to the next subarticle of part 5: <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data/LocalLibrary_base_template">The LocalLibrary base template</a>.</li> +</ul> diff --git a/files/zh-tw/learn/server-side/express_nodejs/forms/create_author_form/index.html b/files/zh-tw/learn/server-side/express_nodejs/forms/create_author_form/index.html new file mode 100644 index 0000000000..9d4563376e --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/forms/create_author_form/index.html @@ -0,0 +1,155 @@ +--- +title: Create Author form +slug: Learn/Server-side/Express_Nodejs/forms/Create_author_form +translation_of: Learn/Server-side/Express_Nodejs/forms/Create_author_form +--- +<p><a class="button section-edit only-icon" href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/forms$edit#Create_author_form" rel="nofollow, noindex"><span>Edi</span></a>本章節演示,如何為創建作者對象 <code>Author</code>定義一個頁面。</p> + +<h2 class="highlight-spanned" id="導入驗證和清理方法">導入驗證和清理方法</h2> + +<p>為了在種類表單使用 <em>express</em> 驗證器,我們必須用 <em>require</em> 導入我們想用的函式。</p> + +<p>打開 <strong>/controllers/authorController.js</strong>,並在檔案最上方,加入底下幾行:</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">const</span> <span class="punctuation token">{</span> body<span class="punctuation token">,</span>validationResult <span class="punctuation token">}</span> <span class="operator token">=</span> <span class="function token">require</span><span class="punctuation token">(</span><span class="string token">'express-validator/check'</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="keyword token">const</span> <span class="punctuation token">{</span> sanitizeBody <span class="punctuation token">}</span> <span class="operator token">=</span> <span class="function token">require</span><span class="punctuation token">(</span><span class="string token">'express-validator/filter'</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<h2 class="highlight-spanned" id="Controller—get_route"><span class="highlight-span">Controller—get route</span></h2> + +<p>Find the exported <code>author_create_get()</code> controller method and replace it with the following code. This simply renders the <strong>author_form.pug</strong> view, passing a <code>title</code> variable.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// Display Author create form on GET.</span> +exports<span class="punctuation token">.</span>author_create_get <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span>req<span class="punctuation token">,</span> res<span class="punctuation token">,</span> next<span class="punctuation token">)</span> <span class="punctuation token">{</span> + res<span class="punctuation token">.</span><span class="function token">render</span><span class="punctuation token">(</span><span class="string token">'author_form'</span><span class="punctuation token">,</span> <span class="punctuation token">{</span> title<span class="punctuation token">:</span> <span class="string token">'Create Author'</span><span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span><span class="punctuation token">;</span></code></pre> + +<h2 class="highlight-spanned" id="Controller—post_route"><span class="highlight-span">Controller—post route</span></h2> + +<p>Find the exported <code>author_create_post()</code> controller method, and replace it with the following code.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// Handle Author create on POST.</span> +exports<span class="punctuation token">.</span>author_create_post <span class="operator token">=</span> <span class="punctuation token">[</span> + + <span class="comment token">// Validate fields.</span> + <span class="function token">body</span><span class="punctuation token">(</span><span class="string token">'first_name'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">isLength</span><span class="punctuation token">(</span><span class="punctuation token">{</span> min<span class="punctuation token">:</span> <span class="number token">1</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">trim</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">withMessage</span><span class="punctuation token">(</span><span class="string token">'First name must be specified.'</span><span class="punctuation token">)</span> + <span class="punctuation token">.</span><span class="function token">isAlphanumeric</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">withMessage</span><span class="punctuation token">(</span><span class="string token">'First name has non-alphanumeric characters.'</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + <span class="function token">body</span><span class="punctuation token">(</span><span class="string token">'family_name'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">isLength</span><span class="punctuation token">(</span><span class="punctuation token">{</span> min<span class="punctuation token">:</span> <span class="number token">1</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">trim</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">withMessage</span><span class="punctuation token">(</span><span class="string token">'Family name must be specified.'</span><span class="punctuation token">)</span> + <span class="punctuation token">.</span><span class="function token">isAlphanumeric</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">withMessage</span><span class="punctuation token">(</span><span class="string token">'Family name has non-alphanumeric characters.'</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + <span class="function token">body</span><span class="punctuation token">(</span><span class="string token">'date_of_birth'</span><span class="punctuation token">,</span> <span class="string token">'Invalid date of birth'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">optional</span><span class="punctuation token">(</span><span class="punctuation token">{</span> checkFalsy<span class="punctuation token">:</span> <span class="keyword token">true</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">isISO8601</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + <span class="function token">body</span><span class="punctuation token">(</span><span class="string token">'date_of_death'</span><span class="punctuation token">,</span> <span class="string token">'Invalid date of death'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">optional</span><span class="punctuation token">(</span><span class="punctuation token">{</span> checkFalsy<span class="punctuation token">:</span> <span class="keyword token">true</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">isISO8601</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + + <span class="comment token">// Sanitize fields.</span> + <span class="function token">sanitizeBody</span><span class="punctuation token">(</span><span class="string token">'first_name'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">trim</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">escape</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + <span class="function token">sanitizeBody</span><span class="punctuation token">(</span><span class="string token">'family_name'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">trim</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">escape</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + <span class="function token">sanitizeBody</span><span class="punctuation token">(</span><span class="string token">'date_of_birth'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">toDate</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + <span class="function token">sanitizeBody</span><span class="punctuation token">(</span><span class="string token">'date_of_death'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">toDate</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + + <span class="comment token">// Process request after validation and sanitization.</span> + <span class="punctuation token">(</span>req<span class="punctuation token">,</span> res<span class="punctuation token">,</span> next<span class="punctuation token">)</span> <span class="operator token">=</span><span class="operator token">></span> <span class="punctuation token">{</span> + + <span class="comment token">// Extract the validation errors from a request.</span> + <span class="keyword token">const</span> errors <span class="operator token">=</span> <span class="function token">validationResult</span><span class="punctuation token">(</span>req<span class="punctuation token">)</span><span class="punctuation token">;</span> + + <span class="keyword token">if</span> <span class="punctuation token">(</span><span class="operator token">!</span>errors<span class="punctuation token">.</span><span class="function token">isEmpty</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// There are errors. Render form again with sanitized values/errors messages.</span> + res<span class="punctuation token">.</span><span class="function token">render</span><span class="punctuation token">(</span><span class="string token">'author_form'</span><span class="punctuation token">,</span> <span class="punctuation token">{</span> title<span class="punctuation token">:</span> <span class="string token">'Create Author'</span><span class="punctuation token">,</span> author<span class="punctuation token">:</span> req<span class="punctuation token">.</span>body<span class="punctuation token">,</span> errors<span class="punctuation token">:</span> errors<span class="punctuation token">.</span><span class="function token">array</span><span class="punctuation token">(</span><span class="punctuation token">)</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="keyword token">return</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + <span class="keyword token">else</span> <span class="punctuation token">{</span> + <span class="comment token">// Data from form is valid.</span> + + <span class="comment token">// Create an Author object with escaped and trimmed data.</span> + <span class="keyword token">var</span> author <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Author</span><span class="punctuation token">(</span> + <span class="punctuation token">{</span> + first_name<span class="punctuation token">:</span> req<span class="punctuation token">.</span>body<span class="punctuation token">.</span>first_name<span class="punctuation token">,</span> + family_name<span class="punctuation token">:</span> req<span class="punctuation token">.</span>body<span class="punctuation token">.</span>family_name<span class="punctuation token">,</span> + date_of_birth<span class="punctuation token">:</span> req<span class="punctuation token">.</span>body<span class="punctuation token">.</span>date_of_birth<span class="punctuation token">,</span> + date_of_death<span class="punctuation token">:</span> req<span class="punctuation token">.</span>body<span class="punctuation token">.</span>date_of_death + <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + author<span class="punctuation token">.</span><span class="function token">save</span><span class="punctuation token">(</span><span class="keyword token">function</span> <span class="punctuation token">(</span>err<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>err<span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="keyword token">return</span> <span class="function token">next</span><span class="punctuation token">(</span>err<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="punctuation token">}</span> + <span class="comment token">// Successful - redirect to new author record.</span> + res<span class="punctuation token">.</span><span class="function token">redirect</span><span class="punctuation token">(</span>author<span class="punctuation token">.</span>url<span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + <span class="punctuation token">}</span> +<span class="punctuation token">]</span><span class="punctuation token">;</span></code></pre> + +<p>The structure and behaviour of this code is almost exactly the same as for creating a <code>Genre</code> object. First we validate and sanitize the data. If the data is invalid then we re-display the form along with the data that was originally entered by the user and a list of error messages. If the data is valid then we save the new author record and redirect the user to the author detail page.</p> + +<div class="note"> +<p><strong>Note:</strong> Unlike with the <code>Genre</code> post handler, we don't check whether the <code>Author</code> object already exists before saving it. Arguably we should, though as it is now we can have multiple authors with the same name.</p> +</div> + +<p>The validation code demonstrates several new features:</p> + +<ul> + <li>We can daisy chain validators, using <code>withMessage()</code> to specify the error message to display if the previous validation method fails. This makes it very easy to provide specific error messages without lots of code duplication. + + <pre class="brush: js">// Validate fields. +body('first_name').isLength({ min: 1 }).trim().withMessage('First name must be specified.') + .isAlphanumeric().withMessage('First name has non-alphanumeric characters.'),<code> +</code></pre> + </li> + <li>We can use the <code>optional()</code> function to run a subsequent validation only if a field has been entered (this allows us to validate optional fields). For example, below we check that the optional date of birth is an ISO8601-compliant date (the <code>checkFalsy</code> flag means that we'll accept either an empty string or <code>null</code> as an empty value). + <pre class="line-numbers language-html"><code class="language-html">body('date_of_birth', 'Invalid date of birth').optional({ checkFalsy: true }).isISO8601(),</code></pre> + </li> +</ul> + +<ul> + <li>Parameters are recieved from the request as strings. We can use <code>toDate()</code> (or <code>toBoolean()</code>, etc.) to cast these to the proper JavaScript types. + + <pre class="brush: js line-numbers language-js"><code class="language-js"><span class="function token">sanitizeBody</span><span class="punctuation token">(</span><span class="string token">'date_of_birth'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">toDate</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span></code></pre> + </li> +</ul> + +<h2 class="highlight-spanned" id="View"><span class="highlight-span">View</span></h2> + +<p>Create <strong>/views/author_form.pug</strong> and copy in the text below.</p> + +<pre class="line-numbers language-html"><code class="language-html">extends layout + +block content + h1=title + + form(method='POST' action='') + div.form-group + label(for='first_name') First Name: + input#first_name.form-control(type='text' placeholder='First name (Christian) last' name='first_name' required='true' value=(undefined===author ? '' : author.first_name) ) + label(for='family_name') Family Name: + input#family_name.form-control(type='text' placeholder='Family name (surname)' name='family_name' required='true' value=(undefined===author ? '' : author.family_name)) + div.form-group + label(for='date_of_birth') Date of birth: + input#date_of_birth.form-control(type='date' name='date_of_birth' value=(undefined===author ? '' : author.date_of_birth) ) + button.btn.btn-primary(type='submit') Submit + if errors + ul + for error in errors + li!= error.msg</code></pre> + +<p>The structure and behaviour for this view is exactly the same as for the <strong>genre_form.pug</strong> template, so we won't describe it again.</p> + +<div class="note"> +<p><strong>Note:</strong> Some browsers don’t support the input <code>type=“date”</code>, so you won’t get the datepicker widget or the default <em><code>dd/mm/yyyy</code></em> placeholder, but will instead get an empty plain text field. One workaround is to explicitly add the attribute <code>placeholder='dd/mm/yyyy'</code> so that on less capable browsers you will still get information about the desired text format.</p> +</div> + +<h3 id="Challenge_Adding_the_date_of_death">Challenge: Adding the date of death</h3> + +<p>The template above is missing a field for entering the <code>date_of_death</code>. Create the field following the same pattern as the date of birth form group!</p> + +<h2 class="highlight-spanned" id="What_does_it_look_like"><span class="highlight-span">What does it look like?</span></h2> + +<p>Run the application, open your browser to <a class="external external-icon" href="http://localhost:3000/" rel="noopener">http://localhost:3000/</a>, then select the <em>Create new author </em>link. If everything is set up correctly, your site should look something like the following screenshot. After you enter a value, it should be saved and you'll be taken to the author detail page.</p> + +<p><img alt="Author Create Page - Express Local Library site" src="https://mdn.mozillademos.org/files/14482/LocalLibary_Express_Author_Create_Empty.png" style="display: block; height: 426px; margin: 0px auto; width: 800px;"></p> + +<div class="note"> +<p><strong>Note:</strong> If you experiment with various input formats for the dates, you may find that the format <code>yyyy-mm-dd</code> misbehaves. This is because JavaScript treats date strings as including the time of 0 hours, but additionally treats date strings in that format (the ISO 8601 standard) as including the time 0 hours UTC, rather than the local time. If your time zone is west of UTC, the date display, being local, will be one day before the date you entered. This is one of several complexities (such as multi-word family names and multi-author books) that we are not addressing here.</p> +</div> + +<h2 id="Next_steps">Next steps</h2> + +<ul> + <li>Return to <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a>.</li> + <li>Proceed to the next subarticle of part 6: <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms/Create_book_form">Create Book form</a>.</li> +</ul> diff --git a/files/zh-tw/learn/server-side/express_nodejs/forms/create_book_form/index.html b/files/zh-tw/learn/server-side/express_nodejs/forms/create_book_form/index.html new file mode 100644 index 0000000000..c15b2ca385 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/forms/create_book_form/index.html @@ -0,0 +1,214 @@ +--- +title: Create Book form +slug: Learn/Server-side/Express_Nodejs/forms/Create_book_form +translation_of: Learn/Server-side/Express_Nodejs/forms/Create_book_form +--- +<p><a class="button section-edit only-icon" href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/forms$edit#Create_book_form" rel="nofollow, noindex">Edit</a>此章節展示如何定義頁面/表單以創建<code>Book</code>對象。這比相同的作者<code>Author</code>或種類<code>Genre</code>頁面稍微複雜一點,因為我們需要在我們的書本表單中,獲取並顯示可用的作者和種類記錄。</p> + +<p> </p> + +<h2 id="導入驗證和清理方法">導入驗證和清理方法</h2> + +<p>打開 <strong>/controllers/bookController.js</strong>,並在文件頂部添加以下幾行:</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">const { body,validationResult } = require('express-validator/check'); +const { sanitizeBody } = require('express-validator/filter');</code></pre> + +<h2 id="Controller—get_route">Controller—get route</h2> + +<p>Find the exported <code>book_create_get()</code> controller method and replace it with the following code.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">// Display book create form on GET. +exports.book_create_get = function(req, res, next) { + + // Get all authors and genres, which we can use for adding to our book. + async.parallel({ + authors: function(callback) { + Author.find(callback); + }, + genres: function(callback) { + Genre.find(callback); + }, + }, function(err, results) { + if (err) { return next(err); } + res.render('book_form', { title: 'Create Book', authors: results.authors, genres: results.genres }); + }); + +};</code></pre> + +<p>This uses the async module (described in <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a>) to get all <code>Author</code> and <code>Genre</code> objects. These are then passed to the view <code><strong>book_form.pug</strong></code> as variables named <code>authors</code> and <code>genres</code> (along with the page <code>title</code>).</p> + +<h2 id="Controller—post_route">Controller—post route</h2> + +<p>Find the exported <code>book_create_post()</code> controller method and replace it with the following code.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">// Handle book create on POST. +exports.book_create_post = [ + // Convert the genre to an array. + (req, res, next) => { + if(!(req.body.genre instanceof Array)){ + if(typeof req.body.genre==='undefined') + req.body.genre=[]; + else + req.body.genre=new Array(req.body.genre); + } + next(); + }, + + // Validate fields. + body('title', 'Title must not be empty.').isLength({ min: 1 }).trim(), + body('author', 'Author must not be empty.').isLength({ min: 1 }).trim(), + body('summary', 'Summary must not be empty.').isLength({ min: 1 }).trim(), + body('isbn', 'ISBN must not be empty').isLength({ min: 1 }).trim(), + + // Sanitize fields (using wildcard). + sanitizeBody('*').trim().escape(), + + // Process request after validation and sanitization. + (req, res, next) => { + + // Extract the validation errors from a request. + const errors = validationResult(req); + + // Create a Book object with escaped and trimmed data. + var book = new Book( + { title: req.body.title, + author: req.body.author, + summary: req.body.summary, + isbn: req.body.isbn, + genre: req.body.genre + }); + + if (!errors.isEmpty()) { + // There are errors. Render form again with sanitized values/error messages. + + // Get all authors and genres for form. + async.parallel({ + authors: function(callback) { + Author.find(callback); + }, + genres: function(callback) { + Genre.find(callback); + }, + }, function(err, results) { + if (err) { return next(err); } + + // Mark our selected genres as checked. + for (let i = 0; i < results.genres.length; i++) { + if (book.genre.indexOf(results.genres[i]._id) > -1) { + results.genres[i].checked='true'; + } + } + res.render('book_form', { title: 'Create Book',authors:results.authors, genres:results.genres, book: book, errors: errors.array() }); + }); + return; + } + else { + // Data from form is valid. Save book. + book.save(function (err) { + if (err) { return next(err); } + //successful - redirect to new book record. + res.redirect(book.url); + }); + } + } +];</code></pre> + +<p>The structure and behaviour of this code is almost exactly the same as for creating a <code>Genre</code> or <code>Author</code> object. First we validate and sanitize the data. If the data is invalid then we re-display the form along with the data that was originally entered by the user and a list of error messages. If the data is valid, we then save the new <code>Book</code> record and redirect the user to the book detail page.</p> + +<p>The first main difference with respect to the other form handling code is that we use a wildcard to trim and escape all fields in one go (rather than sanitising them individually):</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">sanitizeBody('*').trim().escape(),</code></pre> + +<p>The next main difference with respect to the other form handling code is how we sanitize the genre information. The form returns an array of <code>Genre</code> items (while for other fields it returns a string). In order to validate the information we first convert the request to an array (required for the next step).</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">// Convert the genre to an array. +(req, res, next) => { + if(!(req.body.genre instanceof Array)){ + if(typeof req.body.genre==='undefined') + req.body.genre=[]; + else + req.body.genre=new Array(req.body.genre); + } + next(); +},</code></pre> + +<p>We then use a wildcard (<code>*</code>) in the sanitiser to individually validate each of the genre array entries. The code below shows how - this translates to "sanitise every item below key <code>genre</code>".</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">sanitizeBody('genre.*').trim().escape(),</code></pre> + +<p>The final difference with respect to the other form handling code is that we need to pass in all existing genres and authors to the form. In order to mark the genres that were checked by the user we iterate through all the genres and add the <code>checked='true'</code> parameter to those that were in our post data (as reproduced in the code fragment below).</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">// Mark our selected genres as checked. +for (let i = 0; i < results.genres.length; i++) { + if (book.genre.indexOf(results.genres[i]._id) > -1) { + // Current genre is selected. Set "checked" flag. + results.genres[i].checked='true'; + } +}</code></pre> + +<h2 id="View">View</h2> + +<p>Create <strong>/views/book_form.pug</strong> and copy in the text below.</p> + +<pre class="line-numbers language-html"><code class="language-html">extends layout + +block content + h1= title + + form(method='POST' action='') + div.form-group + label(for='title') Title: + input#title.form-control(type='text', placeholder='Name of book' name='title' required='true' value=(undefined===book ? '' : book.title) ) + div.form-group + label(for='author') Author: + select#author.form-control(type='select', placeholder='Select author' name='author' required='true' ) + for author in authors + if book + option(value=author._id selected=(author._id.toString()==book.author ? 'selected' : false) ) #{author.name} + else + option(value=author._id) #{author.name} + div.form-group + label(for='summary') Summary: + input#summary.form-control(type='textarea', placeholder='Summary' name='summary' value=(undefined===book ? '' : book.summary) required='true') + div.form-group + label(for='isbn') ISBN: + input#isbn.form-control(type='text', placeholder='ISBN13' name='isbn' value=(undefined===book ? '' : book.isbn) required='true') + div.form-group + label Genre: + div + for genre in genres + div(style='display: inline; padding-right:10px;') + input.checkbox-input(type='checkbox', name='genre', id=genre._id, value=genre._id, checked=genre.checked ) + label(for=genre._id) #{genre.name} + button.btn.btn-primary(type='submit') Submit + + if errors + ul + for error in errors + li!= error.msg</code></pre> + +<p>The view structure and behaviour is almost the same as for the <strong>genre_form.pug</strong> template.</p> + +<p>The main differences are in how we implement the selection-type fields: <code>Author</code> and <code>Genre</code>.</p> + +<ul> + <li>The set of genres are displayed as checkboxes, using the <code>checked</code> value we set in the controller to determine whether or not the box should be selected.</li> + <li>The set of authors are displayed as a single-selection drop-down list. In this case we determine what author to display by comparing the id of the current author option with the value previously entered by the user (passed in as the <code>book</code> variable). This is highlighted above! + <div class="note"> + <p><strong>Note:</strong> If there is an error in the submitted form, then, when the form is to be re-rendered, the new book's author is identified only with a string (the value of the selected option in the list of authors). By contrast, the existing books' authors have <code>_id</code> properties that are not strings. So to compare the new with the existing we must cast each existing book's author's <code>_id</code> to a string, as shown above.</p> + </div> + </li> +</ul> + +<h2 id="What_does_it_look_like">What does it look like?</h2> + +<p>Run the application, open your browser to <a class="external external-icon" href="http://localhost:3000/" rel="noopener">http://localhost:3000/</a>, then select the <em>Create new book </em>link. If everything is set up correctly, your site should look something like the following screenshot. After you submit a valid book, it should be saved and you'll be taken to the book detail page.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/14484/LocalLibary_Express_Book_Create_Empty.png" style="display: block; height: 498px; margin: 0px auto; width: 1000px;"></p> + +<h2 id="Next_steps">Next steps</h2> + +<p>Return to <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a>.</p> + +<p>Proceed to the next subarticle of part 6: <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms/Create_BookInstance_form">Create BookInstance form</a>.</p> diff --git a/files/zh-tw/learn/server-side/express_nodejs/forms/create_bookinstance_form/index.html b/files/zh-tw/learn/server-side/express_nodejs/forms/create_bookinstance_form/index.html new file mode 100644 index 0000000000..14288f4678 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/forms/create_bookinstance_form/index.html @@ -0,0 +1,150 @@ +--- +title: Create BookInstance form +slug: Learn/Server-side/Express_Nodejs/forms/Create_BookInstance_form +translation_of: Learn/Server-side/Express_Nodejs/forms/Create_BookInstance_form +--- +<p><a class="button section-edit only-icon" href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/forms$edit#Create_BookInstance_form" rel="nofollow, noindex"><span>Edi</span></a>本章節演示如何定義一個頁面/表單,以創建 <code>BookInstance</code> 物件。這很像我們用來創建書本 <code>Book</code> 物件的表單。</p> + +<h2 class="highlight-spanned" id="導入驗證和清理方法">導入驗證和清理方法</h2> + +<p>打開 <strong>/controllers/bookinstanceController.js</strong>,並在檔案最上方,加入以下幾行:</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">const</span> <span class="punctuation token">{</span> body<span class="punctuation token">,</span>validationResult <span class="punctuation token">}</span> <span class="operator token">=</span> <span class="function token">require</span><span class="punctuation token">(</span><span class="string token">'express-validator/check'</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="keyword token">const</span> <span class="punctuation token">{</span> sanitizeBody <span class="punctuation token">}</span> <span class="operator token">=</span> <span class="function token">require</span><span class="punctuation token">(</span><span class="string token">'express-validator/filter'</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<h2 class="highlight-spanned" id="Controller—get_route"><span class="highlight-span">Controller—get route</span></h2> + +<p>At the top of the file, require the <em>Book</em> module (needed because each <code>BookInstance</code> is associated with a particular <code>Book</code>).</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">var</span> Book <span class="operator token">=</span> <span class="function token">require</span><span class="punctuation token">(</span><span class="string token">'../models/book'</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<p>Find the exported <code>bookinstance_create_get()</code> controller method and replace it with the following code.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// Display BookInstance create form on GET.</span> +exports<span class="punctuation token">.</span>bookinstance_create_get <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span>req<span class="punctuation token">,</span> res<span class="punctuation token">,</span> next<span class="punctuation token">)</span> <span class="punctuation token">{</span> + + Book<span class="punctuation token">.</span><span class="function token">find</span><span class="punctuation token">(</span><span class="punctuation token">{</span><span class="punctuation token">}</span><span class="punctuation token">,</span><span class="string token">'title'</span><span class="punctuation token">)</span> + <span class="punctuation token">.</span><span class="function token">exec</span><span class="punctuation token">(</span><span class="keyword token">function</span> <span class="punctuation token">(</span>err<span class="punctuation token">,</span> books<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>err<span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="keyword token">return</span> <span class="function token">next</span><span class="punctuation token">(</span>err<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="punctuation token">}</span> + <span class="comment token">// Successful, so render.</span> + res<span class="punctuation token">.</span><span class="function token">render</span><span class="punctuation token">(</span><span class="string token">'bookinstance_form'</span><span class="punctuation token">,</span> <span class="punctuation token">{</span>title<span class="punctuation token">:</span> <span class="string token">'Create BookInstance'</span><span class="punctuation token">,</span> book_list<span class="punctuation token">:</span>books<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + +<span class="punctuation token">}</span><span class="punctuation token">;</span></code></pre> + +<p>The controller gets a list of all books (<code>book_list</code>) and passes it to the view <code><strong>bookinstance_form.pug</strong></code> (along with the <code>title</code>)</p> + +<h2 class="highlight-spanned" id="Controller—post_route"><span class="highlight-span">Controller—post route</span></h2> + +<p>Find the exported <code>bookinstance_create_post()</code> controller method and replace it with the following code.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// Handle BookInstance create on POST.</span> +exports<span class="punctuation token">.</span>bookinstance_create_post <span class="operator token">=</span> <span class="punctuation token">[</span> + + <span class="comment token">// Validate fields.</span> + <span class="function token">body</span><span class="punctuation token">(</span><span class="string token">'book'</span><span class="punctuation token">,</span> <span class="string token">'Book must be specified'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">isLength</span><span class="punctuation token">(</span><span class="punctuation token">{</span> min<span class="punctuation token">:</span> <span class="number token">1</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">trim</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + <span class="function token">body</span><span class="punctuation token">(</span><span class="string token">'imprint'</span><span class="punctuation token">,</span> <span class="string token">'Imprint must be specified'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">isLength</span><span class="punctuation token">(</span><span class="punctuation token">{</span> min<span class="punctuation token">:</span> <span class="number token">1</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">trim</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + <span class="function token">body</span><span class="punctuation token">(</span><span class="string token">'due_back'</span><span class="punctuation token">,</span> <span class="string token">'Invalid date'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">optional</span><span class="punctuation token">(</span><span class="punctuation token">{</span> checkFalsy<span class="punctuation token">:</span> <span class="keyword token">true</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">isISO8601</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + + <span class="comment token">// Sanitize fields.</span> + <span class="function token">sanitizeBody</span><span class="punctuation token">(</span><span class="string token">'book'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">trim</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">escape</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + <span class="function token">sanitizeBody</span><span class="punctuation token">(</span><span class="string token">'imprint'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">trim</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">escape</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + <span class="function token">sanitizeBody</span><span class="punctuation token">(</span><span class="string token">'status'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">trim</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">escape</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + <span class="function token">sanitizeBody</span><span class="punctuation token">(</span><span class="string token">'due_back'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">toDate</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + + <span class="comment token">// Process request after validation and sanitization.</span> + <span class="punctuation token">(</span>req<span class="punctuation token">,</span> res<span class="punctuation token">,</span> next<span class="punctuation token">)</span> <span class="operator token">=</span><span class="operator token">></span> <span class="punctuation token">{</span> + + <span class="comment token">// Extract the validation errors from a request.</span> + <span class="keyword token">const</span> errors <span class="operator token">=</span> <span class="function token">validationResult</span><span class="punctuation token">(</span>req<span class="punctuation token">)</span><span class="punctuation token">;</span> + + <span class="comment token">// Create a BookInstance object with escaped and trimmed data.</span> + <span class="keyword token">var</span> bookinstance <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">BookInstance</span><span class="punctuation token">(</span> + <span class="punctuation token">{</span> book<span class="punctuation token">:</span> req<span class="punctuation token">.</span>body<span class="punctuation token">.</span>book<span class="punctuation token">,</span> + imprint<span class="punctuation token">:</span> req<span class="punctuation token">.</span>body<span class="punctuation token">.</span>imprint<span class="punctuation token">,</span> + status<span class="punctuation token">:</span> req<span class="punctuation token">.</span>body<span class="punctuation token">.</span>status<span class="punctuation token">,</span> + due_back<span class="punctuation token">:</span> req<span class="punctuation token">.</span>body<span class="punctuation token">.</span>due_back + <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + + <span class="keyword token">if</span> <span class="punctuation token">(</span><span class="operator token">!</span>errors<span class="punctuation token">.</span><span class="function token">isEmpty</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// There are errors. Render form again with sanitized values and error messages.</span> + Book<span class="punctuation token">.</span><span class="function token">find</span><span class="punctuation token">(</span><span class="punctuation token">{</span><span class="punctuation token">}</span><span class="punctuation token">,</span><span class="string token">'title'</span><span class="punctuation token">)</span> + <span class="punctuation token">.</span><span class="function token">exec</span><span class="punctuation token">(</span><span class="keyword token">function</span> <span class="punctuation token">(</span>err<span class="punctuation token">,</span> books<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>err<span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="keyword token">return</span> <span class="function token">next</span><span class="punctuation token">(</span>err<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="punctuation token">}</span> + <span class="comment token">// Successful, so render.</span> + res<span class="punctuation token">.</span><span class="function token">render</span><span class="punctuation token">(</span><span class="string token">'bookinstance_form'</span><span class="punctuation token">,</span> <span class="punctuation token">{</span> title<span class="punctuation token">:</span> <span class="string token">'Create BookInstance'</span><span class="punctuation token">,</span> book_list <span class="punctuation token">:</span> books<span class="punctuation token">,</span> selected_book <span class="punctuation token">:</span> bookinstance<span class="punctuation token">.</span>book<span class="punctuation token">.</span>_id <span class="punctuation token">,</span> errors<span class="punctuation token">:</span> errors<span class="punctuation token">.</span><span class="function token">array</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span> bookinstance<span class="punctuation token">:</span>bookinstance <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="keyword token">return</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + <span class="keyword token">else</span> <span class="punctuation token">{</span> + <span class="comment token">// Data from form is valid.</span> + bookinstance<span class="punctuation token">.</span><span class="function token">save</span><span class="punctuation token">(</span><span class="keyword token">function</span> <span class="punctuation token">(</span>err<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>err<span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="keyword token">return</span> <span class="function token">next</span><span class="punctuation token">(</span>err<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="punctuation token">}</span> + <span class="comment token">// Successful - redirect to new record.</span> + res<span class="punctuation token">.</span><span class="function token">redirect</span><span class="punctuation token">(</span>bookinstance<span class="punctuation token">.</span>url<span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + <span class="punctuation token">}</span> +<span class="punctuation token">]</span><span class="punctuation token">;</span></code></pre> + +<p>The structure and behaviour of this code is the same as for creating our other objects. First we validate and sanitize the data. If the data is invalid, we then re-display the form along with the data that was originally entered by the user and a list of error messages. If the data is valid, we save the new <code>BookInstance</code> record and redirect the user to the detail page.</p> + +<h2 class="highlight-spanned" id="View"><span class="highlight-span">View</span></h2> + +<p>Create <strong>/views/bookinstance_form.pug</strong> and copy in the text below.</p> + +<pre class="line-numbers language-html"><code class="language-html">extends layout + +block content + h1=title + + form(method='POST' action='') + div.form-group + label(for='book') Book: + select#book.form-control(type='select' placeholder='Select book' name='book' required='true') + for book in book_list + if bookinstance + option(value=book._id selected=(bookinstance.book.toString()==book._id.toString() ? 'selected' : false)) #{book.title} + else + option(value=book._id) #{book.title} + + div.form-group + label(for='imprint') Imprint: + input#imprint.form-control(type='text' placeholder='Publisher and date information' name='imprint' required='true' value=(undefined===bookinstance ? '' : bookinstance.imprint)) + div.form-group + label(for='due_back') Date when book available: + input#due_back.form-control(type='date' name='due_back' value=(undefined===bookinstance ? '' : bookinstance.due_back)) + + div.form-group + label(for='status') Status: + select#status.form-control(type='select' placeholder='Select status' name='status' required='true') + option(value='Maintenance') Maintenance + option(value='Available') Available + option(value='Loaned') Loaned + option(value='Reserved') Reserved + + button.btn.btn-primary(type='submit') Submit + + if errors + ul + for error in errors + li!= error.msg</code></pre> + +<p>The view structure and behaviour is almost the same as for the <strong>book_form.pug</strong> template, so we won't go over it again.</p> + +<div class="note"> +<p><strong>Note:</strong> The above template hard-codes the <em>Status</em> values (Maintenance, Available, etc.) and does not "remember" the user's entered values. Should you so wish, consider reimplementing the list, passing in option data from the controller and setting the selected value when the form is re-displayed.</p> +</div> + +<h2 class="highlight-spanned" id="What_does_it_look_like"><span class="highlight-span">What does it look like?</span></h2> + +<p>Run the application and open your browser to <a class="external external-icon" href="http://localhost:3000/" rel="noopener">http://localhost:3000/</a>. Then select the <em>Create new book instance (copy) </em>link. If everything is set up correctly, your site should look something like the following screenshot. After you submit a valid <code>BookInstance</code>, it should be saved and you'll be taken to the detail page.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/14490/LocalLibary_Express_BookInstance_Create_Empty.png" style="display: block; height: 554px; margin: 0px auto; width: 1000px;"></p> + +<h2 id="Next_steps">Next steps</h2> + +<ul> + <li>Return to <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a>.</li> + <li>Proceed to the next subarticle of part 6: <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms/Delete_author_form">Delete Author form</a>.</li> +</ul> diff --git a/files/zh-tw/learn/server-side/express_nodejs/forms/create_genre_form/index.html b/files/zh-tw/learn/server-side/express_nodejs/forms/create_genre_form/index.html new file mode 100644 index 0000000000..3e648e48ea --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/forms/create_genre_form/index.html @@ -0,0 +1,294 @@ +--- +title: 創建種類表單 +slug: Learn/Server-side/Express_Nodejs/forms/Create_genre_form +translation_of: Learn/Server-side/Express_Nodejs/forms/Create_genre_form +--- +<p>本章節演示如何定義我們的頁面,創建<code>Genre</code> 物件(這是一個很好的起點,因為類型<code>Genre</code>只有一個欄位,就是它的名稱 <code>name</code>,沒有依賴項)。像任何其他頁面一樣,我們需要設置路由,控制器和視圖。</p> + +<p> </p> + +<h2 class="highlight-spanned" id="引入驗證與無害化方法">引入驗證與無害化方法</h2> + +<p>在我們的控制器中使用 <em>express-validator</em> 驗證器,我們必須導入我們想要從 '<strong>express-validator/check</strong>' 和 '<strong>express-validator/filter</strong>' 模塊中使用的函數。</p> + +<p>打開 <strong>/controllers/genreController.js</strong>,並在文件頂部添加以下幾行:</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="keyword token">const</span> <span class="punctuation token">{</span> body<span class="punctuation token">,</span>validationResult <span class="punctuation token">}</span> <span class="operator token">=</span> <span class="function token">require</span><span class="punctuation token">(</span><span class="string token">'express-validator/check'</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="keyword token">const</span> <span class="punctuation token">{</span> sanitizeBody <span class="punctuation token">}</span> <span class="operator token">=</span> <span class="function token">require</span><span class="punctuation token">(</span><span class="string token">'express-validator/filter'</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<h2 class="highlight-spanned" id="Controller—get_route"><span class="highlight-span">Controller—get route</span></h2> + +<p>Find the exported <code>genre_create_get()</code> controller method and replace it with the following code. This simply renders the <strong>genre_form.pug</strong> view, passing a title variable.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// Display Genre create form on GET.</span> +exports<span class="punctuation token">.</span>genre_create_get <span class="operator token">=</span> <span class="keyword token">function</span><span class="punctuation token">(</span>req<span class="punctuation token">,</span> res<span class="punctuation token">,</span> next<span class="punctuation token">)</span> <span class="punctuation token">{</span> + res<span class="punctuation token">.</span><span class="function token">render</span><span class="punctuation token">(</span><span class="string token">'genre_form'</span><span class="punctuation token">,</span> <span class="punctuation token">{</span> title<span class="punctuation token">:</span> <span class="string token">'Create Genre'</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +<span class="punctuation token">}</span><span class="punctuation token">;</span></code></pre> + +<h2 class="highlight-spanned" id="Controller—post_route"><span class="highlight-span">Controller—post route</span></h2> + +<p>Find the exported <code>genre_create_post()</code> controller method and replace it with the following code.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// Handle Genre create on POST.</span> +exports<span class="punctuation token">.</span>genre_create_post <span class="operator token">=</span> <span class="punctuation token">[</span> + + <span class="comment token">// Validate that the name field is not empty.</span> + <span class="function token">body</span><span class="punctuation token">(</span><span class="string token">'name'</span><span class="punctuation token">,</span> <span class="string token">'Genre name required'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">isLength</span><span class="punctuation token">(</span><span class="punctuation token">{</span> min<span class="punctuation token">:</span> <span class="number token">1</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">trim</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + + <span class="comment token">// Sanitize (trim and escape) the name field.</span> + <span class="function token">sanitizeBody</span><span class="punctuation token">(</span><span class="string token">'name'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">trim</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">escape</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + + <span class="comment token">// Process request after validation and sanitization.</span> + <span class="punctuation token">(</span>req<span class="punctuation token">,</span> res<span class="punctuation token">,</span> next<span class="punctuation token">)</span> <span class="operator token">=</span><span class="operator token">></span> <span class="punctuation token">{</span> + + <span class="comment token">// Extract the validation errors from a request.</span> + <span class="keyword token">const</span> errors <span class="operator token">=</span> <span class="function token">validationResult</span><span class="punctuation token">(</span>req<span class="punctuation token">)</span><span class="punctuation token">;</span> + + <span class="comment token">// Create a genre object with escaped and trimmed data.</span> + <span class="keyword token">var</span> genre <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Genre</span><span class="punctuation token">(</span> + <span class="punctuation token">{</span> name<span class="punctuation token">:</span> req<span class="punctuation token">.</span>body<span class="punctuation token">.</span>name <span class="punctuation token">}</span> + <span class="punctuation token">)</span><span class="punctuation token">;</span> + + + <span class="keyword token">if</span> <span class="punctuation token">(</span><span class="operator token">!</span>errors<span class="punctuation token">.</span><span class="function token">isEmpty</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// There are errors. Render the form again with sanitized values/error messages.</span> + res<span class="punctuation token">.</span><span class="function token">render</span><span class="punctuation token">(</span><span class="string token">'genre_form'</span><span class="punctuation token">,</span> <span class="punctuation token">{</span> title<span class="punctuation token">:</span> <span class="string token">'Create Genre'</span><span class="punctuation token">,</span> genre<span class="punctuation token">:</span> genre<span class="punctuation token">,</span> errors<span class="punctuation token">:</span> errors<span class="punctuation token">.</span><span class="function token">array</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="keyword token">return</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + <span class="keyword token">else</span> <span class="punctuation token">{</span> + <span class="comment token">// Data from form is valid.</span> + <span class="comment token">// Check if Genre with same name already exists.</span> + Genre<span class="punctuation token">.</span><span class="function token">findOne</span><span class="punctuation token">(</span><span class="punctuation token">{</span> <span class="string token">'name'</span><span class="punctuation token">:</span> req<span class="punctuation token">.</span>body<span class="punctuation token">.</span>name <span class="punctuation token">}</span><span class="punctuation token">)</span> + <span class="punctuation token">.</span><span class="function token">exec</span><span class="punctuation token">(</span> <span class="keyword token">function</span><span class="punctuation token">(</span>err<span class="punctuation token">,</span> found_genre<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>err<span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="keyword token">return</span> <span class="function token">next</span><span class="punctuation token">(</span>err<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="punctuation token">}</span> + + <span class="keyword token">if</span> <span class="punctuation token">(</span>found_genre<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// Genre exists, redirect to its detail page.</span> + res<span class="punctuation token">.</span><span class="function token">redirect</span><span class="punctuation token">(</span>found_genre<span class="punctuation token">.</span>url<span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + <span class="keyword token">else</span> <span class="punctuation token">{</span> + + genre<span class="punctuation token">.</span><span class="function token">save</span><span class="punctuation token">(</span><span class="keyword token">function</span> <span class="punctuation token">(</span>err<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>err<span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="keyword token">return</span> <span class="function token">next</span><span class="punctuation token">(</span>err<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="punctuation token">}</span> + <span class="comment token">// Genre saved. Redirect to genre detail page.</span> + res<span class="punctuation token">.</span><span class="function token">redirect</span><span class="punctuation token">(</span>genre<span class="punctuation token">.</span>url<span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + + <span class="punctuation token">}</span> + + <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + <span class="punctuation token">}</span> +<span class="punctuation token">]</span><span class="punctuation token">;</span></code></pre> + +<p>The first thing to note is that instead of being a single middleware function (with arguments <code>(req, res, next)</code>) the controller specifies an <em>array</em> of middleware functions. The array is passed to the router function and each method is called in order.</p> + +<ul> +</ul> + +<div class="note"> +<p><strong>Note:</strong> This approach is needed, because the sanitisers/validators are middleware functions.</p> +</div> + +<p>The first method in the array defines a validator (<code>body</code>) to check that the <em>name</em> field is not empty (calling <code>trim()</code> to remove any trailing/leading whitespace before performing the validation). The second method in the array (<code>sanitizeBody()</code>) creates a sanitizer to <code>trim()</code> the <em>name</em> field and <code>escape()</code> any dangerous HTML characters.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// Validate that the name field is not empty.</span> +<span class="function token">body</span><span class="punctuation token">(</span><span class="string token">'name'</span><span class="punctuation token">,</span> <span class="string token">'Genre name required'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">isLength</span><span class="punctuation token">(</span><span class="punctuation token">{</span> min<span class="punctuation token">:</span> <span class="number token">1</span> <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">trim</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span> + +<span class="comment token">// Sanitize (trim and escape) the name field.</span> +<span class="function token">sanitizeBody</span><span class="punctuation token">(</span><span class="string token">'name'</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">trim</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">.</span><span class="function token">escape</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">,</span></code></pre> + +<ul> +</ul> + +<div class="note"> +<p><strong>Note:</strong> Sanitizers run during validation do not modify the request. That is why we have to call <code>trim()</code> in both steps above!</p> +</div> + +<p>After specifying the validators and sanitizers we create a middleware function to extract any validation errors. We use <code>isEmpty()</code> to check whether there are any errors in the validation result. If there are then we render the form again, passing in our sanitised genre object and the array of error messages (<code>errors.array()</code>).</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// Process request after validation and sanitization.</span> +<span class="punctuation token">(</span>req<span class="punctuation token">,</span> res<span class="punctuation token">,</span> next<span class="punctuation token">)</span> <span class="operator token">=</span><span class="operator token">></span> <span class="punctuation token">{</span> + + <span class="comment token">// Extract the validation errors from a request.</span> + <span class="keyword token">const</span> errors <span class="operator token">=</span> <span class="function token">validationResult</span><span class="punctuation token">(</span>req<span class="punctuation token">)</span><span class="punctuation token">;</span> + + <span class="comment token">// Create a genre object with escaped and trimmed data.</span> + <span class="keyword token">var</span> genre <span class="operator token">=</span> <span class="keyword token">new</span> <span class="class-name token">Genre</span><span class="punctuation token">(</span> + <span class="punctuation token">{</span> name<span class="punctuation token">:</span> req<span class="punctuation token">.</span>body<span class="punctuation token">.</span>name <span class="punctuation token">}</span> + <span class="punctuation token">)</span><span class="punctuation token">;</span> + + <span class="keyword token">if</span> <span class="punctuation token">(</span><span class="operator token">!</span>errors<span class="punctuation token">.</span><span class="function token">isEmpty</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// There are errors. Render the form again with sanitized values/error messages.</span> + res<span class="punctuation token">.</span><span class="function token">render</span><span class="punctuation token">(</span><span class="string token">'genre_form'</span><span class="punctuation token">,</span> <span class="punctuation token">{</span> title<span class="punctuation token">:</span> <span class="string token">'Create Genre'</span><span class="punctuation token">,</span> genre<span class="punctuation token">:</span> genre<span class="punctuation token">,</span> errors<span class="punctuation token">:</span> errors<span class="punctuation token">.</span><span class="function token">array</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="keyword token">return</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + <span class="keyword token">else</span> <span class="punctuation token">{</span> + <span class="comment token">// Data from form is valid.</span> + <span class="punctuation token">.</span><span class="punctuation token">.</span><span class="punctuation token">.</span> <span class="operator token"><</span>save the result<span class="operator token">></span> <span class="punctuation token">.</span><span class="punctuation token">.</span><span class="punctuation token">.</span> + <span class="punctuation token">}</span> +<span class="punctuation token">}</span></code></pre> + +<p>If the genre name data is valid then we check if a <code>Genre</code> with the same name already exists (as we don't want to create duplicates). If it does we redirect to the existing genre's detail page. If not, we save the new <code>Genre</code> and redirect to its detail page.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js"><span class="comment token">// Check if Genre with same name already exists.</span> +Genre<span class="punctuation token">.</span><span class="function token">findOne</span><span class="punctuation token">(</span><span class="punctuation token">{</span> <span class="string token">'name'</span><span class="punctuation token">:</span> req<span class="punctuation token">.</span>body<span class="punctuation token">.</span>name <span class="punctuation token">}</span><span class="punctuation token">)</span> + <span class="punctuation token">.</span><span class="function token">exec</span><span class="punctuation token">(</span> <span class="keyword token">function</span><span class="punctuation token">(</span>err<span class="punctuation token">,</span> found_genre<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>err<span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="keyword token">return</span> <span class="function token">next</span><span class="punctuation token">(</span>err<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="punctuation token">}</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>found_genre<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="comment token">// Genre exists, redirect to its detail page.</span> + res<span class="punctuation token">.</span><span class="function token">redirect</span><span class="punctuation token">(</span>found_genre<span class="punctuation token">.</span>url<span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> + <span class="keyword token">else</span> <span class="punctuation token">{</span> + genre<span class="punctuation token">.</span><span class="function token">save</span><span class="punctuation token">(</span><span class="keyword token">function</span> <span class="punctuation token">(</span>err<span class="punctuation token">)</span> <span class="punctuation token">{</span> + <span class="keyword token">if</span> <span class="punctuation token">(</span>err<span class="punctuation token">)</span> <span class="punctuation token">{</span> <span class="keyword token">return</span> <span class="function token">next</span><span class="punctuation token">(</span>err<span class="punctuation token">)</span><span class="punctuation token">;</span> <span class="punctuation token">}</span> + <span class="comment token">// Genre saved. Redirect to genre detail page.</span> + res<span class="punctuation token">.</span><span class="function token">redirect</span><span class="punctuation token">(</span>genre<span class="punctuation token">.</span>url<span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> + <span class="punctuation token">}</span> +<span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<p>This same pattern is used in all our post controllers: we run validators, then sanitisers, then check for errors and either re-render the form with error information or save the data. </p> + +<h2 class="highlight-spanned" id="View"><span class="highlight-span">View</span></h2> + +<p>The same view is rendered in both the <code>GET</code> and <code>POST</code> controllers/routes when we create a new <code>Genre</code> (and later on it is also used when we <em>update</em> a <code>Genre</code>). In the <code>GET</code> case the form is empty and we just pass a title variable. In the <code>POST</code> case the user has previously entered invalid data—in the <code>genre</code> variable we pass back a sanitized version of the entered data and in the <code>errors</code> variable we pass back an array of error messages.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">res<span class="punctuation token">.</span><span class="function token">render</span><span class="punctuation token">(</span><span class="string token">'genre_form'</span><span class="punctuation token">,</span> <span class="punctuation token">{</span> title<span class="punctuation token">:</span> <span class="string token">'Create Genre'</span><span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span> +res<span class="punctuation token">.</span><span class="function token">render</span><span class="punctuation token">(</span><span class="string token">'genre_form'</span><span class="punctuation token">,</span> <span class="punctuation token">{</span> title<span class="punctuation token">:</span> <span class="string token">'Create Genre'</span><span class="punctuation token">,</span> genre<span class="punctuation token">:</span> genre<span class="punctuation token">,</span> errors<span class="punctuation token">:</span> errors<span class="punctuation token">.</span><span class="function token">array</span><span class="punctuation token">(</span><span class="punctuation token">)</span><span class="punctuation token">}</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre> + +<p>Create <strong>/views/genre_form.pug</strong> and copy in the text below.</p> + +<pre class="line-numbers language-html"><code class="language-html">extends layout + +block content + h1 #{title} + + form(method='POST' action='') + div.form-group + label(for='name') Genre: + input#name.form-control(type='text', placeholder='Fantasy, Poetry etc.' name='name' value=(undefined===genre ? '' : genre.name)) + button.btn.btn-primary(type='submit') Submit + + if errors + ul + for error in errors + li!= error.msg</code></pre> + +<p>Much of this template will be familiar from our previous tutorials. First we extend the <strong>layout.pug</strong> base template and override the <code>block</code> named '<strong>content</strong>'. We then have a heading with the <code>title</code> we passed in from the controller (via the <code>render()</code> method).</p> + +<p>Next we have the pug code for our HTML form that uses the <code>POST</code> <code>method</code> to send the data to the server, and because the <code>action</code> is an empty string, will send the data to the same URL as the page.</p> + +<p>The form defines a single required field of type "text" called "name". The default <em>value</em> of the field depends on whether the <code>genre</code> variable is defined. If called from the <code>GET</code> route it will be empty as this is a new form. If called from a <code>POST</code> route it will contain the (invalid) value originally entered by the user.</p> + +<p>The last part of the page is the error code. This simply prints a list of errors, if the error variable has been defined (in other words, this section will not appear when the template is rendered on the <code>GET</code> route).</p> + +<div class="note"> +<p><strong>Note:</strong> This is just one way to render the errors. You can also get the names of the affected fields from the error variable, and use these to control where the error messages are rendered, whether to apply custom CSS, etc.</p> +</div> + +<h2 class="highlight-spanned" id="What_does_it_look_like"><span class="highlight-span">What does it look like?</span></h2> + +<p>Run the application, open your browser to <a class="external external-icon" href="http://localhost:3000/" rel="noopener">http://localhost:3000/</a>, then select the <em>Create new genre </em>link. If everything is set up correctly, your site should look something like the following screenshot. After you enter a value, it should be saved and you'll be taken to the genre detail page.</p> + +<p><img alt="Genre Create Page - Express Local Library site" src="https://mdn.mozillademos.org/files/14476/LocalLibary_Express_Genre_Create_Empty.png" style="border-style: solid; border-width: 1px; display: block; height: 301px; margin: 0px auto; width: 800px;"></p> + +<p>The only error we validate against server-side is that the genre field must not be empty. The screenshot below shows what the error list would look like if you didn't supply a genre (highlighted in red).</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/14480/LocalLibary_Express_Genre_Create_Error.png" style="border-style: solid; border-width: 1px; display: block; height: 249px; margin: 0px auto; width: 400px;"></p> + +<div class="note"> +<p><strong>Note:</strong> Our validation uses <code>trim()</code> to ensure that whitespace is not accepted as a genre name. We can also validate that the field is not empty on the client side by adding the value <code>required='true'</code> to the field definition in the form:</p> + +<pre class="brush: js"><code>input#name.form-control(type='text', placeholder='Fantasy, Poetry etc.' name='name' value=(undefined===genre ? '' : genre.name), <strong>required='true'</strong> )</code></pre> +</div> + +<h2 id="Next_steps">Next steps</h2> + +<ul> + <li>Return to <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms.</a></li> + <li>Proceed to the next subarticle of part 6: <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms/Create_author_form">Create Author form</a>.</li> +</ul> + +<div id="SL_balloon_obj" style="display: block;"> +<div class="SL_ImTranslatorLogo" id="SL_button" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; display: none; text-shadow: rgb(0, 0, 0) 0px 0px 1px, rgb(0, 0, 0) 0px 0px 2px, rgb(0, 0, 0) 0px 0px 3px, rgb(0, 0, 0) 0px 0px 4px, rgb(0, 0, 0) 0px 0px 5px !important; opacity: 1;"> </div> + +<div id="SL_shadow_translation_result2" style="display: none;"> </div> + +<div id="SL_shadow_translator" style="display: none;"> +<div id="SL_planshet"> +<div id="SL_arrow_up" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; text-shadow: rgb(0, 0, 0) 0px 0px 1px, rgb(0, 0, 0) 0px 0px 2px, rgb(0, 0, 0) 0px 0px 3px, rgb(0, 0, 0) 0px 0px 4px, rgb(0, 0, 0) 0px 0px 5px !important;"> </div> + +<div id="SL_Bproviders"> +<div class="SL_BL_LABLE_ON" id="SL_P0" title="Google">G</div> + +<div class="SL_BL_LABLE_ON" id="SL_P1" title="Microsoft">M</div> + +<div class="SL_BL_LABLE_ON" id="SL_P2" title="Translator">T</div> +</div> + +<div id="SL_alert_bbl" style="display: none;"> +<div id="SLHKclose" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; text-shadow: rgb(0, 0, 0) 0px 0px 1px, rgb(0, 0, 0) 0px 0px 2px, rgb(0, 0, 0) 0px 0px 3px, rgb(0, 0, 0) 0px 0px 4px, rgb(0, 0, 0) 0px 0px 5px !important;"> </div> + +<div id="SL_alert_cont"> </div> +</div> + +<div id="SL_TB"> +<table id="SL_tables"> + <tbody> + <tr> + <td class="SL_td"><input></td> + <td class="SL_td"><select><option value="auto">Detect language</option><option value="af">Afrikaans</option><option value="sq">Albanian</option><option value="ar">Arabic</option><option value="hy">Armenian</option><option value="az">Azerbaijani</option><option value="eu">Basque</option><option value="be">Belarusian</option><option value="bn">Bengali</option><option value="bs">Bosnian</option><option value="bg">Bulgarian</option><option value="ca">Catalan</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinese (Simplified)</option><option value="zh-TW">Chinese (Traditional)</option><option value="hr">Croatian</option><option value="cs">Czech</option><option value="da">Danish</option><option value="nl">Dutch</option><option value="en">English</option><option value="eo">Esperanto</option><option value="et">Estonian</option><option value="tl">Filipino</option><option value="fi">Finnish</option><option value="fr">French</option><option value="gl">Galician</option><option value="ka">Georgian</option><option value="de">German</option><option value="el">Greek</option><option value="gu">Gujarati</option><option value="ht">Haitian Creole</option><option value="ha">Hausa</option><option value="iw">Hebrew</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="hu">Hungarian</option><option value="is">Icelandic</option><option value="ig">Igbo</option><option value="id">Indonesian</option><option value="ga">Irish</option><option value="it">Italian</option><option value="ja">Japanese</option><option value="jw">Javanese</option><option value="kn">Kannada</option><option value="kk">Kazakh</option><option value="km">Khmer</option><option value="ko">Korean</option><option value="lo">Lao</option><option value="la">Latin</option><option value="lv">Latvian</option><option value="lt">Lithuanian</option><option value="mk">Macedonian</option><option value="mg">Malagasy</option><option value="ms">Malay</option><option value="ml">Malayalam</option><option value="mt">Maltese</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongolian</option><option value="my">Myanmar (Burmese)</option><option value="ne">Nepali</option><option value="no">Norwegian</option><option value="fa">Persian</option><option value="pl">Polish</option><option value="pt">Portuguese</option><option value="pa">Punjabi</option><option value="ro">Romanian</option><option value="ru">Russian</option><option value="sr">Serbian</option><option value="st">Sesotho</option><option value="si">Sinhala</option><option value="sk">Slovak</option><option value="sl">Slovenian</option><option value="so">Somali</option><option value="es">Spanish</option><option value="su">Sundanese</option><option value="sw">Swahili</option><option value="sv">Swedish</option><option value="tg">Tajik</option><option value="ta">Tamil</option><option value="te">Telugu</option><option value="th">Thai</option><option value="tr">Turkish</option><option value="uk">Ukrainian</option><option value="ur">Urdu</option><option value="uz">Uzbek</option><option value="vi">Vietnamese</option><option value="cy">Welsh</option><option value="yi">Yiddish</option><option value="yo">Yoruba</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_switch_b" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; text-shadow: rgb(0, 0, 0) 0px 0px 1px, rgb(0, 0, 0) 0px 0px 2px, rgb(0, 0, 0) 0px 0px 3px, rgb(0, 0, 0) 0px 0px 4px, rgb(0, 0, 0) 0px 0px 5px !important;" title="Switch languages"> </div> + </td> + <td class="SL_td"><select><option value="af">Afrikaans</option><option value="sq">Albanian</option><option value="ar">Arabic</option><option value="hy">Armenian</option><option value="az">Azerbaijani</option><option value="eu">Basque</option><option value="be">Belarusian</option><option value="bn">Bengali</option><option value="bs">Bosnian</option><option value="bg">Bulgarian</option><option value="ca">Catalan</option><option value="ceb">Cebuano</option><option value="ny">Chichewa</option><option value="zh-CN">Chinese (Simplified)</option><option value="zh-TW">Chinese (Traditional)</option><option value="hr">Croatian</option><option value="cs">Czech</option><option value="da">Danish</option><option value="nl">Dutch</option><option selected value="en">English</option><option value="eo">Esperanto</option><option value="et">Estonian</option><option value="tl">Filipino</option><option value="fi">Finnish</option><option value="fr">French</option><option value="gl">Galician</option><option value="ka">Georgian</option><option value="de">German</option><option value="el">Greek</option><option value="gu">Gujarati</option><option value="ht">Haitian Creole</option><option value="ha">Hausa</option><option value="iw">Hebrew</option><option value="hi">Hindi</option><option value="hmn">Hmong</option><option value="hu">Hungarian</option><option value="is">Icelandic</option><option value="ig">Igbo</option><option value="id">Indonesian</option><option value="ga">Irish</option><option value="it">Italian</option><option value="ja">Japanese</option><option value="jw">Javanese</option><option value="kn">Kannada</option><option value="kk">Kazakh</option><option value="km">Khmer</option><option value="ko">Korean</option><option value="lo">Lao</option><option value="la">Latin</option><option value="lv">Latvian</option><option value="lt">Lithuanian</option><option value="mk">Macedonian</option><option value="mg">Malagasy</option><option value="ms">Malay</option><option value="ml">Malayalam</option><option value="mt">Maltese</option><option value="mi">Maori</option><option value="mr">Marathi</option><option value="mn">Mongolian</option><option value="my">Myanmar (Burmese)</option><option value="ne">Nepali</option><option value="no">Norwegian</option><option value="fa">Persian</option><option value="pl">Polish</option><option value="pt">Portuguese</option><option value="pa">Punjabi</option><option value="ro">Romanian</option><option value="ru">Russian</option><option value="sr">Serbian</option><option value="st">Sesotho</option><option value="si">Sinhala</option><option value="sk">Slovak</option><option value="sl">Slovenian</option><option value="so">Somali</option><option value="es">Spanish</option><option value="su">Sundanese</option><option value="sw">Swahili</option><option value="sv">Swedish</option><option value="tg">Tajik</option><option value="ta">Tamil</option><option value="te">Telugu</option><option value="th">Thai</option><option value="tr">Turkish</option><option value="uk">Ukrainian</option><option value="ur">Urdu</option><option value="uz">Uzbek</option><option value="vi">Vietnamese</option><option value="cy">Welsh</option><option value="yi">Yiddish</option><option value="yo">Yoruba</option><option value="zu">Zulu</option></select></td> + <td class="SL_td"> + <div id="SL_TTS_voice" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; text-shadow: rgb(0, 0, 0) 0px 0px 1px, rgb(0, 0, 0) 0px 0px 2px, rgb(0, 0, 0) 0px 0px 3px, rgb(0, 0, 0) 0px 0px 4px, rgb(0, 0, 0) 0px 0px 5px !important;" title="Listen to the translation"> </div> + </td> + <td class="SL_td"> + <div class="SL_copy" id="SL_copy" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; text-shadow: rgb(0, 0, 0) 0px 0px 1px, rgb(0, 0, 0) 0px 0px 2px, rgb(0, 0, 0) 0px 0px 3px, rgb(0, 0, 0) 0px 0px 4px, rgb(0, 0, 0) 0px 0px 5px !important;" title="Copy translation"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_font_patch"> </div> + + <div class="SL_bbl_font" id="SL_bbl_font" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; text-shadow: rgb(0, 0, 0) 0px 0px 1px, rgb(0, 0, 0) 0px 0px 2px, rgb(0, 0, 0) 0px 0px 3px, rgb(0, 0, 0) 0px 0px 4px, rgb(0, 0, 0) 0px 0px 5px !important;" title="Font size"> </div> + </td> + <td class="SL_td"> + <div id="SL_bbl_help" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; text-shadow: rgb(0, 0, 0) 0px 0px 1px, rgb(0, 0, 0) 0px 0px 2px, rgb(0, 0, 0) 0px 0px 3px, rgb(0, 0, 0) 0px 0px 4px, rgb(0, 0, 0) 0px 0px 5px !important;" title="Help"> </div> + </td> + <td class="SL_td"> + <div class="SL_pin_off" id="SL_pin" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; text-shadow: rgb(0, 0, 0) 0px 0px 1px, rgb(0, 0, 0) 0px 0px 2px, rgb(0, 0, 0) 0px 0px 3px, rgb(0, 0, 0) 0px 0px 4px, rgb(0, 0, 0) 0px 0px 5px !important;" title="Pin pop-up bubble"> </div> + </td> + </tr> + </tbody> +</table> +</div> +</div> + +<div id="SL_shadow_translation_result" style=""> </div> + +<div class="SL_loading" id="SL_loading" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; text-shadow: rgb(0, 0, 0) 0px 0px 1px, rgb(0, 0, 0) 0px 0px 2px, rgb(0, 0, 0) 0px 0px 3px, rgb(0, 0, 0) 0px 0px 4px, rgb(0, 0, 0) 0px 0px 5px !important;"> </div> + +<div id="SL_player2"> </div> + +<div id="SL_alert100">Text-to-speech function is limited to 200 characters</div> + +<div id="SL_Balloon_options" style="background: rgb(0, 0, 0) repeat scroll 0% 0%; text-shadow: rgb(0, 0, 0) 0px 0px 1px, rgb(0, 0, 0) 0px 0px 2px, rgb(0, 0, 0) 0px 0px 3px, rgb(0, 0, 0) 0px 0px 4px, rgb(0, 0, 0) 0px 0px 5px !important;"> +<div id="SL_arrow_down" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; text-shadow: rgb(0, 0, 0) 0px 0px 1px, rgb(0, 0, 0) 0px 0px 2px, rgb(0, 0, 0) 0px 0px 3px, rgb(0, 0, 0) 0px 0px 4px, rgb(0, 0, 0) 0px 0px 5px !important;"> </div> + +<table id="SL_tbl_opt" style="width: 100%;"> + <tbody> + <tr> + <td><input></td> + <td> + <div id="SL_BBL_IMG" style="background: rgba(0, 0, 0, 0) repeat scroll 0% 0%; text-shadow: rgb(0, 0, 0) 0px 0px 1px, rgb(0, 0, 0) 0px 0px 2px, rgb(0, 0, 0) 0px 0px 3px, rgb(0, 0, 0) 0px 0px 4px, rgb(0, 0, 0) 0px 0px 5px !important;" title="Show Translator's button 3 second(s)"> </div> + </td> + <td><a class="SL_options" title="Show options">Options</a> : <a class="SL_options" title="Translation History">History</a> : <a class="SL_options" title="ImTranslator Feedback">Feedback</a> : <a class="SL_options" href="https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=GD9D8CPW8HFA2" title="Make a small contribution">Donate</a></td> + <td><span id="SL_Balloon_Close" title="Close">Close</span></td> + </tr> + </tbody> +</table> +</div> +</div> +</div> diff --git a/files/zh-tw/learn/server-side/express_nodejs/forms/delete_author_form/index.html b/files/zh-tw/learn/server-side/express_nodejs/forms/delete_author_form/index.html new file mode 100644 index 0000000000..f26b87bce7 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/forms/delete_author_form/index.html @@ -0,0 +1,167 @@ +--- +title: Delete Author form +slug: Learn/Server-side/Express_Nodejs/forms/Delete_author_form +translation_of: Learn/Server-side/Express_Nodejs/forms/Delete_author_form +--- +<p> </p> + +<p>此子文檔展示,如何定義頁面以刪除 <code>Author</code>對象。</p> + +<p>正如<a href="/zh-TW/docs/Learn/Server-side/Express_Nodejs/forms#form_design">表單設計</a>部分所討論的那樣,我們的策略是,只允許刪除“未被其他對象引用” 的對象(在這種情況下,這意味著如果作者<code>Author</code>被一本書<code>Book</code>引用,我們將不允許刪除作者)。在實現方面,這意味著,表單需要在刪除作者之前,先確認沒有關聯的書籍。如果存在關聯的書籍,則應顯示它們,並說明在刪除<code>Author</code>對象之前,必須刪除它們。</p> + +<h2 class="highlight-spanned" id="Controller—get_route">Controller—get route</h2> + +<p>Open <strong>/controllers/authorController.js</strong>. Find the exported <code>author_delete_get()</code> controller method and replace it with the following code.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">// Display Author delete form on GET. +exports.author_delete_get = function(req, res, next) { + + async.parallel({ + author: function(callback) { + Author.findById(req.params.id).exec(callback) + }, + authors_books: function(callback) { + Book.find({ 'author': req.params.id }).exec(callback) + }, + }, function(err, results) { + if (err) { return next(err); } + if (results.author==null) { // No results. + res.redirect('/catalog/authors'); + } + // Successful, so render. + res.render('author_delete', { title: 'Delete Author', author: results.author, author_books: results.authors_books } ); + }); + +};</code></pre> + +<p>The controller gets the id of the <code>Author</code> instance to be deleted from the URL parameter (<code>req.params.id</code>). It uses the <code>async.parallel()</code> method to get the author record and all associated books in parallel. When both operations have completed it renders the <code><strong>author_delete</strong></code><strong>.pug</strong> view, passing variables for the <code>title</code>, <code>author</code>, and <code>author_books</code>.</p> + +<div class="note"> +<p><strong>Note:</strong> If <code>findById()</code><strong> </strong>returns no results the author is not in the database. In this case there is nothing to delete, so we immediately render the list of all authors. </p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">}, function(err, results) { + if (err) { return next(err); } + if (results.author==null) { // No results. + res.redirect('/catalog/authors') + }</code></pre> +</div> + +<h2 class="highlight-spanned" id="Controller—post_route">Controller—post route</h2> + +<p>Find the exported <code>author_delete_post()</code> controller method, and replace it with the following code.</p> + +<pre class="brush: js line-numbers language-js"><code class="language-js">// Handle Author delete on POST. +exports.author_delete_post = function(req, res, next) { + + async.parallel({ + author: function(callback) { + Author.findById(req.body.authorid).exec(callback) + }, + authors_books: function(callback) { + Book.find({ 'author': req.body.authorid }).exec(callback) + }, + }, function(err, results) { + if (err) { return next(err); } + // Success + if (results.authors_books.length > 0) { + // Author has books. Render in same way as for GET route. + res.render('author_delete', { title: 'Delete Author', author: results.author, author_books: results.authors_books } ); + return; + } + else { + // Author has no books. Delete object and redirect to the list of authors. + Author.findByIdAndRemove(req.body.authorid, function deleteAuthor(err) { + if (err) { return next(err); } + // Success - go to author list + res.redirect('/catalog/authors') + }) + } + }); +};</code></pre> + +<p>First we validate that an id has been provided (this is sent via the form body parameters, rather than using the version in the URL). Then we get the author and their associated books in the same way as for the <code>GET</code> route. If there are no books then we delete the author object and redirect to the list of all authors. If there are still books then we just re-render the form, passing in the author and list of books to be deleted.</p> + +<div class="note"> +<p><strong>Note:</strong> We could check if the call to <code>findById()</code><strong> </strong>returns any result, and if not, immediately render the list of all authors. We've left the code as it is above for brevity (it will still return the list of authors if the id is not found, but this will happen after <code>findByIdAndRemove()</code>).</p> +</div> + +<h2 class="highlight-spanned" id="View">View</h2> + +<p>Create <strong>/views/author_delete.pug</strong> and copy in the text below.</p> + +<pre class="line-numbers language-html"><code class="language-html">extends layout + +block content + h1 #{title}: #{author.name} + p= author.lifespan + + if author_books.length + + p #[strong Delete the following books before attempting to delete this author.] + + div(style='margin-left:20px;margin-top:20px') + + h4 Books + + dl + each book in author_books + dt + a(href=book.url) #{book.title} + dd #{book.summary} + + else + p Do you really want to delete this Author? + + form(method='POST' action='') + div.form-group + input#authorid.form-control(type='hidden',name='authorid', required='true', value=author._id ) + + button.btn.btn-primary(type='submit') Delete</code></pre> + +<p>The view extends the layout template, overriding the block named <code>content</code>. At the top it displays the author details. It then includes a conditional statement based on the number of <code><strong>author_books</strong></code> (the <code>if</code> and <code>else</code> clauses).</p> + +<ul> + <li>If there <em>are</em> books associated with the author then the page lists the books and states that these must be deleted before this <code>Author</code> may be deleted.</li> + <li>If there <em>are no</em> books then the page displays a confirmation prompt. If the <strong>Delete</strong> button is clicked then the author id is sent to the server in a <code>POST</code> request and that author's record will be deleted.</li> +</ul> + +<h2 class="highlight-spanned" id="Add_a_delete_control">Add a delete control</h2> + +<p>Next we will add a <strong>Delete</strong> control to the<em> Author detail</em> view (the detail page is a good place from which to delete a record).</p> + +<div class="note"> +<p><strong>Note:</strong> In a full implementation the control would be made visible only to authorised users. However at this point we haven't got an authorisation system in place!</p> +</div> + +<p>Open the <strong>author_detail.pug</strong> view and add the following lines at the bottom.</p> + +<pre class="brush: html line-numbers language-html"><code class="language-html">hr +p + a(href=author.url+'/delete') Delete author</code></pre> + +<p>The control should now appear as a link, as shown below on the <em>Author detail</em> page.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/14492/LocalLibary_Express_Author_Detail_Delete.png" style="border-style: solid; border-width: 1px; display: block; height: 202px; margin: 0px auto; width: 500px;"></p> + +<h2 class="highlight-spanned" id="What_does_it_look_like">What does it look like?</h2> + +<p>Run the application and open your browser to <a class="external external-icon" href="http://localhost:3000/" rel="noopener">http://localhost:3000/</a>. Then select the <em>All authors </em>link, and then select a particular author. Finally select the <em>Delete author</em> link.</p> + +<p>If the author has no books, you'll be presented with a page like this. After pressing delete, the server will delete the author and redirect to the author list.</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/14494/LocalLibary_Express_Author_Delete_NoBooks.png" style="border-style: solid; border-width: 1px; display: block; height: 342px; margin: 0px auto; width: 600px;"></p> + +<p>If the author does have books, then you'll be presented with a view like the following. You can then delete the books from their detail pages (once that code is implemented!).</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/14496/LocalLibary_Express_Author_Delete_WithBooks.png" style="border-style: solid; border-width: 1px; display: block; height: 327px; margin: 0px auto; width: 500px;"></p> + +<div class="note"> +<p><strong>Note:</strong> The other pages for deleting objects can be implemented in much the same way. We've left that as a challenge.</p> +</div> + +<h2 id="Next_steps">Next steps</h2> + +<ul> + <li>Return to <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a>.</li> + <li>Proceed to the final subarticle of part 6: <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms/Update_Book_form">Update Book form</a>.</li> +</ul> diff --git a/files/zh-tw/learn/server-side/express_nodejs/forms/index.html b/files/zh-tw/learn/server-side/express_nodejs/forms/index.html new file mode 100644 index 0000000000..008d7ae4e8 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/forms/index.html @@ -0,0 +1,274 @@ +--- +title: 'Express 教學 6: 使用表單' +slug: Learn/Server-side/Express_Nodejs/forms +translation_of: Learn/Server-side/Express_Nodejs/forms +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Displaying_data", "Learn/Server-side/Express_Nodejs/deployment", "Learn/Server-side/Express_Nodejs")}}</div> + +<p class="summary">在此教程中,我們會教你如何使用 Express ,並且結合 Pug 來實現 HTML 表單,並且如何從數據庫中創建、更新、和刪除文檔。</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">前提條件:</th> + <td>完成前面所有的教程,包括 Express 教程第5章: 展示圖書館數據。</td> + </tr> + <tr> + <th scope="row">目標:</th> + <td>了解如何編寫表單獲取用戶信息,並且將這些數據更新到數據庫中。</td> + </tr> + </tbody> +</table> + +<h2 id="概覽">概覽</h2> + +<p><a href="/zh-TW/docs/Web/Guide/HTML/Forms">HTML 表單</a>是網頁中由一個、或多個字段/小工具形成的一個組合,它被用來收集用戶的信息,並將信息上傳到服務器。表單作為一種用來收集用戶的機制,非常的靈活,因為有各種合適的輸入框,來接受各種類型的數據——文本框,複選框,單選按鈕,時間選擇器等。表單和服務器交互數據也相對安全,因為它使用<code>POST</code>請求發送數據,保護不受跨站點請求偽造攻擊(cross-site request forgery)的威脅。</p> + +<p>但是表單同樣也很複雜!開發者需要編寫給表單編寫 HTML,在服務器上驗證,並且正確去除有害的數據(瀏覽器上也可能需要),對於任何不合法的字段,需要傳給用戶相應的錯誤信息,當數據成功提交後,處理數據,並設法通知用戶提交成功。</p> + +<p>此教程將展示上述的操作,如何在 Express 中實現。在此過程中,我們將擴展 LocalLibrary 網站,以允許用戶創建、編輯、和刪除圖書館中的項目。</p> + +<div class="note"> +<p><strong>注意:</strong> 我們還沒有考慮如何將特定路由,限制為經過身份驗證或授權的用戶,因此在這個時間點,任何用戶都可以對數據庫進行更改。</p> +</div> + +<h3 id="HTML_表單">HTML 表單</h3> + +<p>首先簡要概述 <a href="/zh-TW/docs/Web/Guide/HTML/Forms">HTML 表單</a>。考慮一個簡單的 HTML 表單,其中包含一個文本字段,用於輸入某些 “團隊” 的名稱,及其相關標籤:</p> + +<p><img alt="Simple name field example in HTML form" src="https://mdn.mozillademos.org/files/14117/form_example_name_field.png" style="border-style: solid; border-width: 1px; display: block; height: 44px; margin: 0px auto; width: 399px;"></p> + +<p>表單在HTML中,定義為 <code><form>...</form></code>標記內的元素集合,包含至少一個<code>type="submit"</code>的 <code>input</code>輸入元素。</p> + +<pre class="brush: html"><form action="/team_name_url/" method="post"> + <label for="team_name">Enter name: </label> + <input id="team_name" type="text" name="name_field" value="Default name for team."> + <input type="submit" value="OK"> +</form></pre> + +<p>雖然這裡,我們只包含一個(文本)字段,用於輸入團隊名稱,但表單可能包含任意數量的其他輸入元素,及其相關標籤。字段的 <code>type</code> 屬性,定義將顯示哪種窗口小部件。該字段的名稱<code>name</code>和<code>id</code> ,用於標識JavaScript/CSS/HTML 中的字段,而 <code>value</code>定義字段首次顯示時的初始值。匹配團隊標籤使用 <code style="font-style: normal; font-weight: normal;">label </code>標籤,指定(請參閱上面的“輸入名稱” "Enter name"),其中 <code style="font-style: normal; font-weight: normal;">for</code> 字段,包含 <code style="font-style: normal; font-weight: normal;">input </code>相關輸入的 <code style="font-style: normal; font-weight: normal;">id</code>值。</p> + +<p>提交輸入(<code>submit</code>)將顯示為按鈕(默認情況下) - 用戶可以按此按鈕,將其他輸入元素包含的數據,上傳到服務器(在本例中,只有 <code>team_name</code>)。表單屬性,定義用於發送數據的HTTP <code>method</code>方法,和服務器上數據的目標(<code>action</code>):</p> + +<ul> + <li><code>action</code>: 提交表單時,要發送數據以進行處理的資源/ URL。如果未設置(或設置為空字符串),則表單將提交回當前頁面 URL。</li> + <li><code>method</code>: 用於發送數據的 HTTP 方法:<code>POST</code> 或 <code>GET</code>。 + <ul> + <li><code>POST</code> 方法。如果數據將導致服務器數據庫的更改,則始終應該使用 <code>POST</code>方法,因為這更加可以抵抗跨站點偽造請求攻擊。</li> + <li><code>GET</code> 方法只應用於不更改用戶數據的表單(例如,搜索表單)。當您希望能夠為URL添加書籤或共享時,建議使用此選項。</li> + </ul> + </li> +</ul> + +<h3 id="表單處理流程">表單處理流程</h3> + +<p>表單處理使用的技術,與我們學習過、用來顯示有關模型的信息的所有技術,是相同的:路由將我們的請求發送到控制器函數,該函數執行所需的任何數據庫操作,包括從模型中讀取數據,然後生成並返回 HTML 頁面。使事情變得更複雜的是,服務器還需要能夠處理用戶提供的數據,並在出現任何問題時,重新顯示帶有錯誤信息的表單。</p> + +<p>下面顯示了處理表單請求的流程圖,從包含表單的頁面請求開始(以綠色顯示):</p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/14478/Web%20server%20form%20handling.png" style="height: 649px; width: 800px;"></p> + +<p>如上圖所示,構成處理代碼所需要做的主要是: </p> + +<ol> + <li>在用戶第一次請求時顯示默認表單。 + <ul> + <li>表單可能包含空白字段(例如,如果您正在創建新記錄),或者可能預先填充了初始值(例如,如果您要更改記錄,或者俱有有用的默認初始值)。</li> + </ul> + </li> + <li>接收用戶提交的數據,通常是在HTTP <code>POST</code>請求中。</li> + <li>驗證並清理數據。</li> + <li>如果任何數據無效,請重新顯示表單 - 這次使用用戶填寫的任何值,和問題字段的錯誤消息。</li> + <li>如果所有數據都有效,請執行所需的操作(例如,將數據保存在數據庫中,發送通知電子郵件,返回搜索結果,上傳文件等)</li> + <li>完成所有操作之後,將用戶重定向到另一個頁面。</li> +</ol> + +<p>表格處理代碼,通常使用 <code>GET</code>路由,以實現表單的初始顯示,以及 <code>POST</code>路由到同一路徑,以處理表單數據的驗證和處理。這是將在本教程中使用的方法!</p> + +<p>Express 本身不提供表單處理操作的任何特定支持,但它可以使用中間件,以處理表單中的 <code>POST</code>和 <code>GET</code>參數,並驗證/清理它們的值。</p> + +<h3 id="驗證和清理">驗證和清理</h3> + +<p>在儲存表單中的數據之前,必須對其進行驗證和清理:</p> + +<ul> + <li>驗證檢查輸入的值,適用於每個字段(範圍,格式等),並且已為所有必填字段提供了值。</li> + <li>數據中的字符,可能用於將惡意內容送到服務器,為其進行清理刪除/替換。</li> +</ul> + +<p>在本教程中,我們將使用流行的 <a href="https://www.npmjs.com/package/express-validator">express-validator </a>模塊,來執行表單數據的驗證和清理。</p> + +<h4 id="安裝">安裝</h4> + +<p>通過在項目的根目錄中,運行以下命令,來安裝模塊。</p> + +<pre class="brush: bash">npm install express-validator +</pre> + +<h4 id="使用_express-validator">使用 express-validator</h4> + +<div class="note"> +<p><strong>注意:</strong> Github上的 <a href="https://github.com/ctavan/express-validator#express-validator">express-validator</a> 指南,提供了API的良好概述。我們建議您閱讀該內容,以了解其所有功能(包括創建自定義驗證程序)。下面我們只介紹一個對 LocalLibrary 有用的子集。</p> + +<p> </p> + +<p> </p> +</div> + +<p>要在我們的控制器中使用驗證器,我們必須從 'e<strong>xpress-validator/check</strong>'和'<strong>express-validator/filter</strong>'模塊中,導入我們想要使用的函數,如下所示:</p> + +<pre class="brush: js">const { body,validationResult } = require('express-validator/check'); +const { sanitizeBody } = require('express-validator/filter'); +</pre> + +<p>有許多可用的功能,允許您一次檢查和清理請求參數,正文,標頭,cookie 等數據,或所有數據。對於本教程,我們主要使用 <code>body</code>, <code>sanitizeBody</code>,和 <code>validationResult</code>(如上面 required 導入的 )。</p> + +<p>功能定義如下:</p> + +<ul> + <li><code><a href="https://github.com/ctavan/express-validator#bodyfields-message">body(fields[, message])</a></code>: 指定請求本文中的一組字段(<code>POST</code>參數)以及可選的錯誤消息,如果測試失敗,則可以顯示該字段。驗證標準以菊花鏈形式連接到 <code>body()</code>方法。例如,下面的第一個檢查測試,“name”字段不為空,如果不是,則設置錯誤消息“Empty name”。第二個測試,檢查age字段是否為有效日期,並使用<code>optional()</code>指定null和空字符串不會驗證失敗。 + + <pre class="brush: js">body('name', 'Empty name').isLength({ min: 1 }), +body('age', 'Invalid age').optional({ checkFalsy: true }).isISO8601(), +</pre> + 您還可以用菊花鍊式連接不同的驗證器,並添加前面驗證器為真時顯示的消息。 + + <pre class="brush: js">body('name').isLength({ min: 1 }).trim().withMessage('Name empty.') + .isAlpha().withMessage('Name must be alphabet letters.'), +</pre> + + <div class="note"> + <p><strong>注意:</strong> 您還可以添加內聯清理器,如<code>trim()</code>,如上所示。但是,此處應用清理器,僅適用於驗證步驟。如果要對最終輸出進行消毒,則需要使用單獨的清理器方法,如下所示。</p> + </div> + </li> + <li><code><a href="https://github.com/ctavan/express-validator#sanitizebodyfields">sanitizeBody(fields)</a></code>: 指定一個正文要清理的字段。然後將清理操作,以菊花鏈形式連接到此方法。例如,下面的 <code>escape()</code>清理操作,會從名稱變量中,刪除可能在 JavaScript 跨站點腳本攻擊中使用的 HTML 字符。 + <pre class="brush: js">sanitizeBody('name').trim().escape(), +sanitizeBody('date').toDate(),</pre> + </li> + <li><code><a href="https://github.com/ctavan/express-validator#validationresultreq">validationResult(req)</a></code>: 運行驗證,以 <code>validation </code>驗證結果對象的形式,提供錯誤。這是在單獨的回調中調用的,如下所示: + <pre class="brush: js">(req, res, next) => { + // Extract the validation errors from a request. + const errors = validationResult(req); + + if (!errors.isEmpty()) { + // There are errors. Render form again with sanitized values/errors messages. + // Error messages can be returned in an array using `errors.array()`. + } + else { + // Data from form is valid. + } +}</pre> + 我們使用驗證結果的<code>isEmpty()</code>方法,來檢查是否存在錯誤,並使用其 <code>array()</code> 方法,來獲取錯誤消息集合。有關更多信息,請參閱驗證結果的 <a href="https://github.com/ctavan/express-validator#validation-result-api">Validation Result API</a>。</li> +</ul> + +<p>驗證和清理鏈,是應該傳遞給 Express 路由處理程序的中間件(我們通過控制器,間接地執行此操作)。中間件運行時,每個驗證器/清理程序都按指定的順序運行。</p> + +<p>當我們實現下面的LocalLibrary表單時,我們將介紹一些真實的例子。</p> + +<h3 id="表單設計">表單設計</h3> + +<p>圖書館中的許多模型都是相關/依賴的 - 例如,一本書需要一個作者,也可能有一個或多個種類。這提出了一個問題,即我們應該如何處理用戶希望的情況:</p> + +<ul> + <li>在其相關對象尚不存在時,創建對象(例如,尚未定義作者對象的書)。<br> + </li> + <li>刪除另一個對象仍在使用的對象(例如,刪除仍有書本 <code>Book </code>使用的種類 <code>Genre</code>)。</li> +</ul> + +<p>在這個項目,我們為了簡化實作,將聲明表單只能:</p> + +<ul> + <li>使用已存在的對象創建對象(因此用戶在嘗試創建任何 <code>Book</code>對象之前,必須創建任何所需的 <code>Author</code>和 <code>Genre</code>實例)。</li> + <li>如果對象未被其他對象引用,則刪除該對象(例如,在刪除所有關聯的 <code>BookInstance</code>對象之前,您將無法刪除該書)。</li> +</ul> + +<div class="note"> +<p><strong>注意:</strong> 更“牢固”的實現,可能允許您在創建新對象時,創建依賴對象,並隨時刪除任何對象(例如,通過刪除依賴對象,或從數據庫中,刪除對已刪除對象的引用) 。</p> +</div> + +<h3 id="路由">路由</h3> + +<p>為了實現我們的表單處理代碼,我們需要兩個具有相同 URL 模式的路由。</p> + +<p>第一個(<code>GET</code>)路由,用於顯示用於創建對象的新空表單。第二個路由(<code>POST</code>),用於驗證用戶輸入的數據,然後保存信息,並重定向到詳細信息頁面(如果數據有效),或重新顯示有錯誤的表單(如果數據無效)。</p> + +<p>我們已經在 <strong>/routes/catalog.js</strong>(在之前的教程中)為我們所有模型的創建頁面,創建了路徑。例如,種類路由如下所示:</p> + +<pre class="brush: js">// GET request for creating a Genre. NOTE This must come before route that displays Genre (uses id). +router.get('/genre/create', genre_controller.genre_create_get); + +// POST request for creating Genre. +router.post('/genre/create', genre_controller.genre_create_post); +</pre> + +<h2 id="Express_表單子文件">Express 表單子文件</h2> + +<p>以下子文件,將帶我們完成向示例應用程序添加所需表單的過程。在進入下一個文件之前,您需要依次閱讀並解決每個問題。</p> + +<ol> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms/Create_genre_form">創建種類表單</a> — 定義我們的頁面以創建種類對象 <code>Genre </code>。</li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms/Create_author_form">創建作者表單</a> — 定義用於創建作者對象 <code>Author </code>的頁面。</li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms/Create_book_form">創建書本表單</a> — 定義頁面/表單以創建書本對象 <code>Book</code> 。</li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms/Create_BookInstance_form">創建書本實例表單</a> — 定義頁面/表單以創建書本實例對象 <code>BookInstance</code> 。</li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms/Delete_author_form">刪除作者表單 </a>— 定義要刪除作者對象 <code>Author </code>的頁面。</li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms/Update_Book_form">更新書本表單</a> — 定義頁面以更新書本對象 <code>Book</code> 。</li> +</ol> + +<h2 id="挑戰自我">挑戰自我</h2> + +<p>實現 <code>Book</code>, <code>BookInstance</code>, 和 <code>Genre</code>模型的刪除頁面,用跟我們的作者刪除頁面相同的方式,將它們與關聯的詳細信息頁面,鏈接起來。頁面應遵循相同的設計方法:</p> + +<ul> + <li>如果有來自其他對象的、對於對象的引用,則應顯示註釋,列出這些對象,並說明在刪除列出的對象之前,無法刪除此記錄。</li> + <li>如果沒有對該對象的其他引用,則視圖應提示刪除它。如果用戶按下“刪除”按鈕 <strong>Delete</strong>,則應刪除該記錄。</li> +</ul> + +<p>一些提示:</p> + +<ul> + <li>刪除種類 <code>Genre</code>就像刪除作者<code>Author</code>一樣,因為兩個對像都是 <code>Book</code>的依賴項(因此在這兩種情況下,只有在刪除相關書本時,才能刪除對象)。</li> + <li>刪除書本 <code>Book</code>也很相似,但您需要檢查是否沒有關聯的書本實例 <code>BookInstances</code>。</li> + <li>刪除書本實例 <code>BookInstances</code>是最簡單的,因為沒有依賴對象。在這種情況下,您只需找到相關記錄並將其刪除即可。</li> +</ul> + +<p>實現 <code>BookInstance</code>, <code>Author</code>, 和 <code>Genre</code>模型的更新頁面,以與我們的書本更新頁面相同的方式,將它們與關聯的詳細信息頁面,鏈接起來。</p> + +<p>一些提示:</p> + +<ul> + <li>我們剛剛實施的圖書更新頁面是最難的!相同的模式可用於其他對象的更新頁面。</li> + <li>作者<code>Author</code>的死亡日期和出生日期字段,以及書本實例<code>BookInstance</code> 的 due_date 字段,是輸入到表單上日期輸入字段的錯誤格式(它需要 “YYYY-MM-DD” 形式的數據)。解決此問題的最簡單方法,是為適當格式化的日期,定義新的虛擬屬性,然後在關聯的視圖模板中,使用此字段。</li> + <li>如果您遇到困難,此處示例中的更新頁面有一些示例<a href="https://github.com/mdn/express-locallibrary-tutorial">的連結。</a></li> +</ul> + +<h2 id="總結">總結</h2> + +<p>Express, node, 與NPM上面的第三方套件,提供你需要的每樣東西 ,可用於新增表單到你的網站上。在本文中,您學習如何使用 Pug 創建表單,使用 express-validator 驗證和清理輸入,以及添加,刪除和修改數據庫中的記錄。</p> + +<p>你現在應該了解如何新增基本表單,以及表單處理代碼到你的 node 網站!</p> + +<h2 id="請參閱">請參閱</h2> + +<ul> + <li><a href="https://www.npmjs.com/package/express-validator">express-validator</a> (npm docs).</li> +</ul> + +<p>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Displaying_data", "Learn/Server-side/Express_Nodejs/deployment", "Learn/Server-side/Express_Nodejs")}}</p> + +<h2 id="本教程連結">本教程連結</h2> + +<ul> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node introduction</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">Setting up a Node (Express) development environment</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Express Tutorial: The Local Library website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Express Tutorial Part 2: Creating a skeleton website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Express Tutorial Part 3: Using a Database (with Mongoose)</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/routes">Express Tutorial Part 4: Routes and controllers</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/deployment">Express Tutorial Part 7: Deploying to production</a></li> +</ul> + +<p> </p> diff --git a/files/zh-tw/learn/server-side/express_nodejs/index.html b/files/zh-tw/learn/server-side/express_nodejs/index.html new file mode 100644 index 0000000000..c1c6e11ee5 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/index.html @@ -0,0 +1,73 @@ +--- +title: Express web framework (Node.js/JavaScript) +slug: Learn/Server-side/Express_Nodejs +tags: + - Express + - Express.js + - Node + - node.js + - 介紹 + - 伺服器端程式 + - 初學者 + - 學習 +translation_of: Learn/Server-side/Express_Nodejs +--- +<div>{{LearnSidebar}}</div> + +<p class="summary">Express 是一個流行的web框架,使用JavsScript實現,執行在node.js環境上。本系列解釋Express的優點、如何設定開發環境、完成常見的web開發和佈署。</p> + +<h2 id="前置需求">前置需求</h2> + +<p>在開始前你需要了解什麼是伺服器端web程式和什麼是web框架,推薦閱讀<a href="https://developer.mozilla.org/zh-TW/docs/Learn/Server-side/First_steps">伺服器端網站開發第一步</a>。建議了解基本的程式知識和<a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript">JavaScript</a>,但不需要知道核心概念。</p> + +<div class="note"> +<p><strong>注意</strong>: 本網站有許多學習JavaScript應用在客戶端開發的有用資源,如:<a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript">JavaScript</a>、<a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide">JavaScript 指南</a>、<a href="https://developer.mozilla.org/zh-TW/docs/Learn/Getting_started_with_the_web/JavaScript_basics">JavaScript 基礎</a>、<a href="https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript">JavaScript</a> (learning)。使用Node.js開發伺服器端使用的JavaScript語言與概念和客戶端是一樣的。Node.js提供<a href="https://nodejs.org/dist/latest-v6.x/docs/api/">額外的APIs</a>以支援無瀏覽器環境,例如:建立HTTP服務和讀取檔案系統。但不支援DOM及瀏覽器相關的 JavaScript API。</p> + +<p>這份指南將提供一些使用Node.js和Express的資訊以及數個優秀的學習資源。部分連結由 <a href="http://stackoverflow.com/a/5511507/894359">How do I get started with Node.js</a>(StackOverflow) 與 <a href="https://www.quora.com/What-are-the-best-resources-for-learning-Node-js?">What are the best resources for learning Node.js?</a>(Quora) 提供。</p> +</div> + +<h2 id="指南">指南</h2> + +<dl> + <dt><a href="https://developer.mozilla.org/zh-TW/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node 介紹</a></dt> + <dd>第一篇的系列文章中回答了「什麼是Node」和「什麼是Express?」並概略的說明為什麼Express web框架如此特別。此文章將重點放在主要的功能上,並展示一些Express應用常見的建構模塊(儘管此時你還沒有可供測試的開發環境)</dd> + <dt><a href="https://developer.mozilla.org/zh-TW/docs/Learn/Server-side/Express_Nodejs/development_environment">設定 Node (Express) 開發環境</a></dt> + <dd>現在你已經了解Express的目的了,接下來繼續說明如何設定和測試 Windows、Linux (Ubuntu)和Mac OS X上的Node/Express開發環境。不管你用的是什麼作業系統,你都能在本文中找到開發Express應用的入門需知。</dd> + <dt><a href="https://developer.mozilla.org/zh-TW/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Express 教學(1): The Local Library website</a></dt> + <dd>在第一篇實務教學系列文章中將說明你將會學到什麼?以及提供範例網站local library的概覽,我們將在後續的文章中繼續改進它。</dd> + <dt><a href="https://developer.mozilla.org/zh-TW/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Express 教學(2): 建構網站骨架</a></dt> + <dd>本文章展示如何建構網站的骨架,接著你可以自己添加路由、模板/畫面和資料庫。</dd> + <dt><a href="https://developer.mozilla.org/zh-TW/docs/Learn/Server-side/Express_Nodejs/mongoose">Express 教學(3): 使用資料庫(以Mongoose為例)</a></dt> + <dd>本文簡短的介紹Node/Express如何使用資料庫。接下來展示LocalLibray網站如何透過<a href="http://mongoosejs.com/">Mongoose</a>進行資料庫的存取。說明物件綱要(object schema)和模型(models)如何宣告、the main field types和基本驗證。同時簡單的展示幾個讀取資料的主要方法。</dd> + <dt><a href="https://developer.mozilla.org/zh-TW/docs/Learn/Server-side/Express_Nodejs/routes">Express 教學(4): 路由和控制器</a></dt> + <dd>在本教學中,我們將為LocalLibrary網站中的所有資源終端設定“虛擬”處理函數的路由(URL處理代碼)。 完成後,我們將為我們的路由處理程式提供模組化結構,以便我們可以在後續的教學中擴展真正的處理函數。 我們也將了解如何使用Express創建模組化路由。</dd> + <dt><a href="https://developer.mozilla.org/zh-TW/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express 教學(5): 顯示圖書館的資料</a></dt> + <dd>現在已經準備好新增頁面來展示館藏和其他資料了。這些頁面包括一個展示我們有多少種model 型態的首頁、所有models的列表和詳細資料頁面。透過本教學你可以得到從資料庫取得紀錄和使用模板的實務經驗。</dd> + <dt><a href="https://developer.mozilla.org/zh-TW/docs/Learn/Server-side/Express_Nodejs/forms">Express 教學(6): 使用表單</a></dt> + <dd>本教學中展示如何使用Express的插件-Pug來使用HTML Forms,以及如何編寫表單來創造、更新和刪除資料庫的文件。</dd> + <dt><a href="https://developer.mozilla.org/zh-TW/docs/Learn/Server-side/Express_Nodejs/deployment">Express 教學(7): 網站佈署</a></dt> + <dd>現在你完成了很棒的<em>LocalLibrary</em> 網站,你希望圖書館的員工和會員可以透過網路讀取它。本教學概略說明如何找到主機來佈署你的網站以及為了使你的網站正式上線所需做的準備。</dd> +</dl> + +<h2 id="或許你也想看">或許你也想看</h2> + +<dl> + <dt><a href="https://developer.mozilla.org/zh-TW/docs/Learn/Server-side/Express_Nodejs/Installing_on_PWS_Cloud_Foundry">在 PWS/Cloud Foundry上安裝LocalLibrary</a></dt> + <dd>本文展示如何在<a href="http://run.pivotal.io">Pivotal Web Services PaaS cloud</a>上安裝<em>LocalLibrary</em> ,PWS/Cloud Foundry是一個完整且開源的Heroku替代品,可使用於教學(7)。如果你正在尋找Heroku或其他PaaS的替代品或只是想玩點不同的東西,那PWS/Cloud Foundry絕對值得一試。</dd> +</dl> + +<h2 id="新增其他教學">新增其他教學</h2> + +<div> +<p>現在已經有了很多教學,但你可能會想寫其他有趣主題的模塊,包括:</p> + +<ul> + <li>Using sessions</li> + <li>使用者認證</li> + <li>使用者授權與權限</li> + <li>測試Express web應用</li> + <li>Express web 應用之安全性</li> +</ul> + +<p>當然,如果能作個評估模塊就更好了!</p> +</div> diff --git a/files/zh-tw/learn/server-side/express_nodejs/introduction/index.html b/files/zh-tw/learn/server-side/express_nodejs/introduction/index.html new file mode 100644 index 0000000000..6fc3f0a98c --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/introduction/index.html @@ -0,0 +1,522 @@ +--- +title: Express/Node introduction +slug: Learn/Server-side/Express_Nodejs/Introduction +tags: + - Express + - Node + - nodejs + - 伺服器端 + - 初學者 + - 學習 +translation_of: Learn/Server-side/Express_Nodejs/Introduction +--- +<div> + + + + +<p>{{LearnSidebar}}</p> + +<p>{{NextMenu("Learn/Server-side/Express_Nodejs/development_environment", "Learn/Server-side/Express_Nodejs")}}</p> +</div> + +<p class="summary">在這篇文章中回答了「什麼是Node?」和「什麼是Express」,同時概述是什麼讓Express框架如此特別。本文將概述主要特性、展示一些Express應用的主要建構模塊(雖然此時你還沒有能測試它的開發環境)</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">前置需求:</th> + <td>基本的電腦知識。 對<a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/First_steps">伺服器端網站程式設計</a>的基本了解,特別是網站中<a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/First_steps/Client-Server_overview">客戶端 - 伺服器交互的機制</a>。</td> + </tr> + <tr> + <th scope="row">目標:</th> + <td>提升對Express的了解、如何與Node搭配使用、提供的功能和Express應用的主要建構模塊。</td> + </tr> + </tbody> +</table> + +<h2 id="什麼是Express和Node">什麼是Express和Node?</h2> + +<p><a href="https://nodejs.org/">Node</a> (或者說<em>Node.js</em>) 是一個開源、跨平台和允許開發者使用<a href="https://developer.mozilla.org/en-US/docs/Glossary/JavaScript">Javascript</a>創造伺服器端工具和應用的執行環境。運行的目的是為了能在瀏覽器外使用,例如:直接執行在電腦或伺服器上。所以該環境捨棄了瀏覽器限定的JavaScript APIs並增加更多傳統OS APIs的支援,例如:HTTP和檔案系統的程式庫。</p> + + + +<p>從網站伺服器開發的觀點來看Node有幾項優點:</p> + +<ul> + <li>高效能!Node 旨在提升生產率和網頁應用的可擴充性。而且它非常適合網站開發常見的問題,例如:即時網站應用</li> + <li>使用舊版本的JavaScript進行程式編寫,這表示不用多花力氣在轉換瀏覽器和伺服器上的程式碼</li> + <li>與其他傳統的Web伺服器語言(例如Python,PHP等)相比,JavaScript是一種相對新的程式語言,它受益於語言設計的改進。許多其他新的和流行的語言都可以編譯/轉換成JavaScript,因此你還可以使用CoffeeScript, ClojureScript,Scala,LiveScript等</li> + <li>Node Package Manager(NPM) 提供數十萬個第三方套件,是最佳的依賴解決方案也可以用來自動化大部分構建工具鏈。</li> + <li>它是可移植的,能夠在Windows, OS x, Linux, Solaris, FreeBSD, OpenBSD, WebOS和NonStop OS上執行。許多web主機提供方也支援使用Node,通常會提供特定的基礎設施和文件</li> + <li>擁有非常活耀的第三方生態系統和開發者社群,許多人樂意提供幫助</li> +</ul> + +<p>你可以只用Node的HTTP模組創造一個簡單的web伺服器來回應任何請求,如下所示。此教學不會告訴建議的檔案名稱或如何執行該檔案 ;-)</p> + +<p>這將創造一個伺服器並會監聽<code>http://127.0.0.1:8000/</code>上任何種類的HTTP請求,當接收到任何請求時回傳一個「Hello World」的純文字回應。</p> + +<pre class="brush: js">// 載入 HTTP 模組 +var http = require("http"); + +// 創建 HTTP 伺服器並監聽8000 port +http.createServer(function(request, response) { + + // Set the response HTTP header with HTTP status and Content type + response.writeHead(200, {'Content-Type': 'text/plain'}); + + // Send the response body "Hello World" + response.end('Hello World\n'); +}).listen(8000); + +// Print URL for accessing server +console.log('Server running at http://127.0.0.1:8000/');</pre> + +<p>Node並不原生支持其他常見的web開發任務,如果你想為不同的HTTP方法(例如:<code>GET</code>, <code>POST</code>, <code>DELETE</code>等)增加特定的處理、替不同的URL路徑提供靜態檔案、使用樣板或動態性的產生response,你需要自己完成相關的程式<strong>或者是</strong>避免重新造輪子 - 使用web框架!</p> + +<p><a href="https://expressjs.com/">Express</a> 是最受歡迎的Node web框架,還是其他許多流行的<a href="https://expressjs.com/en/resources/frameworks.html">Node web框架</a>的底層庫,它提供:</p> + +<ul> + <li>替不同HTTP Method、不同URL路徑的requests編寫不同的處理方法</li> + <li>透過整合「畫面」的渲染引擎來達到插入資料到樣板中產生response</li> + <li>設定常見的web應用設定,例如:連線用的port和產生response的樣板位置</li> + <li>在request的處理流程中增加額外的「中間層」進行處理</li> +</ul> + +<p>雖然Express本身非常簡單,但開發者們已經創造相容的中間層套件來解決大部份web開發的問題,這些套件能處理cookies, sessions,登入,URL參數,POST資料,安全標頭等等,你能在<a href="http://expressjs.com/en/resources/middleware.html">Express Middleware</a>中找到這些套件的列表(以及其他流行的第三方套件)</p> + +<div class="note"> +<p><strong>注意:</strong> 這種靈活性是一把雙刃劍。有一些中間層套件能解決大部份的問題或需求,但使用正確的套件有時會是一個問題。也沒有「正確的方法」來創建應用,你在網路上找到的範例也並非都是最佳解或是只有開發上所需要做的一小部份。</p> +</div> + +<h2 id="歷史">歷史</h2> + +<p>2009年Node在Linux平台上初次發佈. 2010年NPM套件管利器發佈, 2012年增加Windows的原生支援. 現在的LTS版本為Node v8.11.2,最新版本為Node v10.1.0。這只是它深厚歷史的一小片斷,欲知更多詳情請洽 <a href="https://en.wikipedia.org/wiki/Node.js#History">Wikipedia</a>。</p> + +<p>2010年11月Express初次發佈,現在的API版本為 4.16。你可以查閱<a href="https://expressjs.com/en/changelog/4x.html">更新紀錄</a>來了解此版本做了甚麼更改或是從<a href="https://github.com/expressjs/express/blob/master/History.md">GitHub</a>中了解詳細的歷史紀錄。</p> + +<h2 id="NodeExpress有多流行">Node/Express有多流行?</h2> + +<p>對於web 框架而言流行度很重要,這代表他會不會被繼續更新、文件、附加套件和技術支援方面有多少資源</p> + +<p>現在沒有一個明確的指標來評斷伺服器端框架的流行度,雖然有 <a href="http://hotframeworks.com/">Hot Frameworks</a>透過計算GitHub的專案數量和StackOverflow的問題來衡量流行度。更好的問題是,Node和Express是否「夠流行」以避免成為不流行的平台。有沒有持續進步?需要時是否能得到幫助?能不能找到Express相關的工作?</p> + +<p>從眾多使用Express的<a href="https://expressjs.com/en/resources/companies-using-express.html">公司</a>、貢獻程式碼的人數和那些提供免費/收費支援的人員來看,是的!Express是一個流行的框架。</p> + +<h2 id="Is_Express_opinionated">Is Express opinionated?</h2> + +<p>Web 框架通常自稱為 "opinionated" 或 "unopinionated".</p> + +<p>Opinionated指的是那些有「正確」方法解決特定問題的框架。在特定的需求上他們通常能快速開發,因為正確的方法通常易懂且有良好的文件,然而在面對其他問題時則會失去靈活性。這類型的框架通常傾向於提供較少的選擇和套件來解決問題。</p> + +<p>反過來說Unopinionated 框架,對於如何組合套件來解決問題尚有較少的限制,開發者可以更輕易的使用適當的套件來解決特定問題,儘管代價是你需要自己找到適合的套件。</p> + +<p>Express是Unopinionated 框架,你可以在request處理流程中使用任何相容套件,使用單一或複數個檔案來建構應用,有時候甚至會覺得擁有太多選擇了。</p> + +<h2 id="Express的程式碼長怎樣">Express的程式碼長怎樣?</h2> + +<p>傳統的資料驅動網站中,web應用程式會等待來自瀏覽器(或其他客戶端)的HTTP Request,接收到Request後根據URL和可能夾帶的<code>POST</code>/<code>GET</code>資料來決定需要回應什麼動作,根據需要可能對資料庫進行讀寫或執行滿足Request所需的其他任務。web應用程式會回應Response給瀏覽器,通常是藉由插入檢所到的資料到HTML 模板中動態產生HTML頁面讓瀏覽器顯示。</p> + + + +<p>Express provides methods to specify what function is called for a particular HTTP verb (<code>GET</code>, <code>POST</code>, <code>SET</code>, etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response. You can use Express middleware to add support for cookies, sessions, and users, getting <code>POST</code>/<code>GET</code> parameters, etc. You can use any database mechanism supported by Node (Express does not define any database-related behaviour).</p> + +<p>The following sections explain some of the common things you'll see when working with <em>Express</em> and <em>Node</em> code.</p> + +<h3 id="Helloworld_Express">Helloworld Express</h3> + +<p>First lets consider the standard Express <a href="https://expressjs.com/en/starter/hello-world.html">Hello World</a> example (we discuss each part of this below, and in the following sections).</p> + +<div class="note"> +<p><strong>Tip:</strong> If you have Node and Express already installed (or if you install them as shown in the <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">next article</a>), you can save this code in a text file called <strong>app.js</strong> and run it in a bash command prompt by calling: </p> + +<p><strong><code>./node ./app.js</code></strong></p> +</div> + +<pre class="brush: js">var express = require('express'); +var app = express(); + +<strong>app.get('/', function(req, res) { + res.send('Hello World!'); +});</strong> + +app.listen(3000, function() { + console.log('Example app listening on port 3000!'); +}); +</pre> + +<p>The first two lines <code>require()</code> (import) the express module and create an <a href="https://expressjs.com/en/4x/api.html#app">Express application</a>. This object, which is traditionally named <code>app</code>, has methods for routing HTTP requests, configuring middleware, rendering HTML views, registering a template engine, and modifying <a href="https://expressjs.com/en/4x/api.html#app.settings.table">application settings</a> that control how the application behaves (e.g. the environment mode, whether route definitions are case sensitive, etc.)</p> + +<p>The middle part of the code (the three lines starting with <code>app.get</code>) shows a <em>route definition</em>. The <code>app.get()</code> method specifies a callback function that will be invoked whenever there is an HTTP <code>GET</code> request with a path (<code>'/'</code>) relative to the site root. The callback function takes a request and a response object as arguments, and simply calls <code><a href="https://expressjs.com/en/4x/api.html#res.send">send()</a></code> on the response to return the string "Hello World!"</p> + +<p>The final block starts up the server on port '3000' and prints a log comment to the console. With the server running, you could go to <code>localhost:3000</code> in your browser to see the example response returned.</p> + +<h3 id="Importing_and_creating_modules">Importing and creating modules</h3> + +<p>A module is a JavaScript library/file that you can import into other code using Node's <code>require()</code> function. <em>Express</em> itself is a module, as are the middleware and database libraries that we use in our <em>Express</em> applications.</p> + +<p>The code below shows how we import a module by name, using the <em>Express</em> framework as an example. First we invoke the <code style="font-style: normal; font-weight: normal;">require()</code> function, specifying the name of the module as a string (<code>'express'</code>), and calling the returned object to create an <a href="https://expressjs.com/en/4x/api.html#app">Express application</a>. We can then access the properties and functions of the application object.</p> + +<pre class="brush: js">var express = require('express'); +var app = express(); +</pre> + +<p>You can also create your own modules that can be imported in the same way.</p> + +<div class="note"> +<p><strong>Tip:</strong> You will <em>want </em>to create your own modules, because this allows you to organise your code into managable parts — a monolithic single-file application is hard to understand and maintain. Using modules also helps you manage your namespace, because only the variables you explicitly export are imported when you use a module.</p> +</div> + +<p>To make objects available outside of a module you just need to assign them to the <code>exports</code> object. For example, the <strong>square.js</strong> module below is a file that exports <code>area()</code> and <code>perimeter()</code> methods:</p> + +<pre class="brush: js">exports.area = function(width) { return width * width; }; +exports.perimeter = function(width) { return 4 * width; }; +</pre> + +<p>We can import this module using <code>require()</code>, and then call the exported method(s) as shown:</p> + +<pre class="brush: js">var square = require('./square'); // Here we require() the name of the file without the (optional) .js file extension +console.log('The area of a square with a width of 4 is ' + square.area(4));</pre> + +<div class="note"> +<p><strong>Note:</strong> You can also specify an absolute path to the module (or a name, as we did initially).</p> +</div> + +<p>If you want to export a complete object in one assignment instead of building it one property at a time, assign it to <code>module.exports</code> as shown below (you can also do this to make the root of the exports object a constructor or other function):</p> + +<pre class="brush: js">module.exports = { + area: function(width) { + return width * width; + }, + + perimeter: function(width) { + return 4 * width; + } +}; +</pre> + +<p>For a lot more information about modules see <a href="https://nodejs.org/api/modules.html#modules_modules">Modules</a> (Node API docs).</p> + +<h3 id="Using_asynchronous_APIs">Using asynchronous APIs</h3> + +<p>JavaScript code frequently uses asynchronous rather than synchronous APIs for operations that may take some time to complete. A synchronous API is one in which each operation must complete before the next operation can start. For example, the following log functions are synchronous, and will print the text to the console in order (First, Second).</p> + +<pre class="brush: js">console.log('First'); +console.log('Second'); +</pre> + +<p>By contrast, an asynchronous API is one in which the API will start an operation and immediately return (before the operation is complete). Once the operation finishes, the API will use some mechanism to perform additional operations. For example, the code below will print out "Second, First" because even though <code>setTimeout()</code> method is called first, and returns immediately, the operation doesn't complete for several seconds.</p> + +<pre class="brush: js">setTimeout(function() { + console.log('First'); + }, 3000); +console.log('Second'); +</pre> + +<p>Using non-blocking asynchronous APIs is even more important on Node than in the browser, because <em>Node</em> is a single threaded event-driven execution environment. "single threaded" means that all requests to the server are run on the same thread (rather than being spawned off into separate processes). This model is extremely efficient in terms of speed and server resources, but it does mean that if any of your functions call synchronous methods that take a long time to complete, they will block not just the current request, but every other request being handled by your web application.</p> + +<p>There are a number of ways for an asynchronous API to notify your application that it has completed. The most common way is to register a callback function when you invoke the asynchronous API, that will be called back when the operation completes. This is the approach used above.</p> + +<div class="note"> +<p><strong>Tip:</strong> Using callbacks can be quite "messy" if you have a sequence of dependent asynchronous operations that must be performed in order, because this results in multiple levels of nested callbacks. This problem is commonly known as "callback hell". This problem can be reduced by good coding practices (see <a href="http://callbackhell.com/">http://callbackhell.com/</a>), using a module like <a href="https://www.npmjs.com/package/async">async</a>, or even moving to ES6 features like <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promises</a>.</p> +</div> + +<div class="note"> +<p><strong>Note:</strong> A common convention for Node and Express is to use error-first callbacks. In this convention the first value in your <em>callback functions</em> is an error value, while subsequent arguments contain success data. There is a good explanation of why this approach is useful in this blog: <a href="http://fredkschott.com/post/2014/03/understanding-error-first-callbacks-in-node-js">The Node.js Way - Understanding Error-First Callbacks</a> (fredkschott.com).</p> +</div> + +<h3 id="Creating_route_handlers">Creating route handlers</h3> + +<p>In our <em>Hello World</em> Express example (see above), we defined a (callback) route handler function for HTTP <code>GET</code> requests to the site root (<code>'/'</code>).</p> + +<pre class="brush: js">app.<strong>get</strong>('/', function(req, res) { + res.send('Hello World!'); +}); +</pre> + +<p>The callback function takes a request and a response object as arguments. In this case the method simply calls <code><a href="https://expressjs.com/en/4x/api.html#res.send">send()</a></code> on the response to return the string "Hello World!" There are a <a href="https://expressjs.com/en/guide/routing.html#response-methods">number of other response methods</a> for ending the request/response cycle, for example you could call <code><a href="https://expressjs.com/en/4x/api.html#res.json">res.json()</a></code> to send a JSON response or <code><a href="https://expressjs.com/en/4x/api.html#res.sendFile">res.sendFile()</a></code> to send a file.</p> + +<div class="note"> +<p><strong>JavaScript tip:</strong> You can use any argument names you like in the callback functions; when the callback is invoked the first argument will always be the request and the second will always be the response. It makes sense to name them such that you can identify the object you're working with in the body of the callback.</p> +</div> + +<p>The <em>Express application</em> object also provides methods to define route handlers for all the other HTTP verbs, which are mostly used in exactly the same way: <code>post()</code>, <code>put()</code>, <code>delete()</code>, <code>options()</code>, <code>trace()</code>, <code>copy()</code>, <code>lock()</code>, <code>mkcol()</code>, <code>move()</code>, <code>purge()</code>, <code>propfind()</code>, <code>proppatch()</code>, <code>unlock()</code>, <code>report()</code>, <code>mkactivity()</code>, <code>checkout()</code>, <code>merge()</code>, <code>m-</code><code>search()</code>, <code>notify()</code>, <code>subscribe()</code>, <code>unsubscribe()</code>, <code>patch()</code>, <code>search()</code>, and <code>connect()</code>.</p> + +<p>There is a special routing method, <code>app.all()</code>, which will be called in response to any HTTP method. This is used for loading middleware functions at a particular path for all request methods. The following example (from the Express documentation) shows a handler that will be executed for requests to <code>/secret</code> irrespective of the HTTP verb used (provided it is supported by the <a href="https://nodejs.org/api/http.html#http_http_methods">http module</a>).</p> + +<pre class="brush: js">app.all('/secret', function(req, res, next) { + console.log('Accessing the secret section ...'); + next(); // pass control to the next handler +});</pre> + +<p>Routes allow you to match particular patterns of characters in a URL, and extract some values from the URL and pass them as parameters to the route handler (as attributes of the request object passed as a parameter).</p> + +<p>Often it is useful to group route handlers for a particular part of a site together and access them using a common route-prefix (e.g. a site with a Wiki might have all wiki-related routes in one file and have them accessed with a route prefix of <em>/wiki/</em>). In <em>Express</em> this is achieved by using the <code><a href="http://expressjs.com/en/guide/routing.html#express-router">express.Router</a></code> object. For example, we can create our wiki route in a module named <strong>wiki.js</strong>, and then export the <code>Router</code> object, as shown below:</p> + +<pre class="brush: js">// wiki.js - Wiki route module + +var express = require('express'); +var router = express.Router(); + +// Home page route +router.get('/', function(req, res) { + res.send('Wiki home page'); +}); + +// About page route +router.get('/about', function(req, res) { + res.send('About this wiki'); +}); + +module.exports = router; +</pre> + +<div class="note"> +<p><strong>Note:</strong> Adding routes to the <code>Router</code> object is just like adding routes to the <code>app</code> object (as shown previously).</p> +</div> + +<p>To use the router in our main app file we would then <code>require()</code> the route module (<strong>wiki.js</strong>), then call <code>use()</code> on the <em>Express</em> application to add the Router to the middleware handling path. The two routes will then be accessible from <code style="font-style: normal; font-weight: normal;">/wiki/</code> and <code style="font-style: normal; font-weight: normal;">/wiki/about/</code>.</p> + +<pre class="brush: js">var wiki = require('./wiki.js'); +// ... +app.use('/wiki', wiki);</pre> + +<p>We'll show you a lot more about working with routes, and in particular about using the <code>Router</code>, later on in the linked section<a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/routes"> Routes and controllers .</a></p> + +<h3 id="Using_middleware">Using middleware</h3> + +<p>Middleware is used extensively in Express apps, for tasks from serving static files to error handling, to compressing HTTP responses. Whereas route functions end the HTTP request-response cycle by returning some response to the HTTP client, middleware functions <em>typically</em> perform some operation on the request or response and then call the next function in the "stack", which might be more middleware or a route handler. The order in which middleware is called is up to the app developer.</p> + +<div class="note"> +<p><strong>Note:</strong> The middleware can perform any operation, execute any code, make changes to the request and response object, and it can<em> also end the request-response cycle</em>. If it does not end the cycle then it must call <code>next()</code> to pass control to the next middleware function (or the request will be left hanging).</p> +</div> + +<p>Most apps will use <em>third-party</em> middleware in order to simplify common web development tasks like working with cookies, sessions, user authentication, accessing request <code>POST</code> and JSON data, logging, etc. You can find a <a href="http://expressjs.com/en/resources/middleware.html">list of middleware packages maintained by the Express team</a> (which also includes other popular 3rd party packages). Other Express packages are available on the NPM package manager.</p> + +<p>To use third party middleware you first need to install it into your app using NPM. For example, to install the <a href="http://expressjs.com/en/resources/middleware/morgan.html">morgan</a> HTTP request logger middleware, you'd do this:</p> + +<pre class="brush: bash"><code>$ npm install morgan +</code></pre> + +<p>You could then call <code>use()</code> on the <em>Express application object</em> to add the middleware to the stack:</p> + +<pre class="brush: js">var express = require('express'); +<strong>var logger = require('morgan');</strong> +var app = express(); +<strong>app.use(logger('dev'));</strong> +...</pre> + +<div class="note"> +<p><strong>Note:</strong> Middleware and routing functions are called in the order that they are declared. For some middleware the order is important (for example if session middleware depends on cookie middleware, then the cookie handler must be added first). It is almost always the case that middleware is called before setting routes, or your route handlers will not have access to functionality added by your middleware.</p> +</div> + +<p>You can write your own middleware functions, and you are likely to have to do so (if only to create error handling code). The <strong>only</strong> difference between a middleware function and a route handler callback is that middleware functions have a third argument <code>next</code>, which middleware functions are expected to call if they are not that which completes the request cycle (when the middleware function is called, this contains the <em>next</em> function that must be called).</p> + +<p>You can add a middleware function to the processing chain with either <code>app.use()</code> or <code>app.add()</code>, depending on whether you want to apply the middleware to all responses or to responses with a particular HTTP verb (<code>GET</code>, <code>POST</code>, etc). You specify routes the same in both cases, though the route is optional when calling <strong>app.use()</strong>.</p> + +<p>The example below shows how you can add the middleware function using both methods, and with/without a route.</p> + +<pre class="brush: js">var express = require('express'); +var app = express(); + +// An example middleware function +var a_middleware_function = function(req, res, <em>next</em>) { + // ... perform some operations + next(); // Call next() so Express will call the next middleware function in the chain. +} + +// Function added with use() for all routes and verbs +app.use(a_middleware_function); + +// Function added with use() for a specific route +app.use('/someroute', a_middleware_function); + +// A middleware function added for a specific HTTP verb and route +app.get('/', a_middleware_function); + +app.listen(3000);</pre> + +<div class="note"> +<p><strong>JavaScript Tip:</strong> Above we declare the middleware function separately and then set it as the callback. In our previous route handler function we declared the callback function when it was used. In JavaScript, either approach is valid.</p> +</div> + +<p>The Express documentation has a lot more excellent documentation about <a href="https://expressjs.com/en/guide/using-middleware.html">using</a> and <a href="http://expressjs.com/en/guide/writing-middleware.html">writing</a> Express middleware.</p> + +<h3 id="Serving_static_files">Serving static files</h3> + +<p>You can use the <a href="http://expressjs.com/en/4x/api.html#express.static">express.static</a> middleware to serve static files, including your images, CSS and JavaScript (<code>static()</code> is the only middleware function that is actually <strong>part</strong> of <em>Express</em>). For example, you would use the line below to serve images, CSS files, and JavaScript files from a directory named '<strong>public'</strong> at the same level as where you call node:</p> + +<pre class="brush: js">app.use(express.static('public')); +</pre> + +<p>Any files in the public directory are served by adding their filename (<em>relative</em> to the base "public" directory) to the base URL. So for example:</p> + +<pre><code>http://localhost:3000/images/dog.jpg +http://localhost:3000/css/style.css +http://localhost:3000/js/app.js +http://localhost:3000/about.html +</code></pre> + +<p>You can call <code>static()</code> multiple times to serve multiple directories. If a file cannot be found by one middleware function then it will simply be passed on to the subsequent middleware (the order that middleware is called is based on your declaration order).</p> + +<pre class="brush: js">app.use(express.static('public')); +app.use(express.static('media')); +</pre> + +<p>You can also create a virtual prefix for your static URLs, rather than having the files added to the base URL. For example, here we <a href="http://expressjs.com/en/4x/api.html#app.use">specify a mount path</a> so that the files are loaded with the prefix "/media":</p> + +<pre class="brush: js">app.use('/media', express.static('public')); +</pre> + +<p>Now, you can load the files that are in the <code>public</code> directory from the <code>/media</code> path prefix.</p> + +<pre><code>http://localhost:3000/media/images/dog.jpg +http://localhost:3000/media/video/cat.mp4 +http://localhost:3000/media/cry.mp3</code> +</pre> + +<p>For more information, see <a href="Serving static files in Express">Serving static files in Express</a>.</p> + +<h3 id="Handling_errors">Handling errors</h3> + +<p>Errors are handled by one or more special middleware functions that have four arguments, instead of the usual three: <code>(err, req, res, next)</code>. For example:</p> + +<pre class="brush: js">app.use(function(err, req, res, next) { + console.error(err.stack); + res.status(500).send('Something broke!'); +}); +</pre> + +<p>These can return any content required, but must be called after all other <code>app.use()</code> and routes calls so that they are the last middleware in the request handling process!</p> + +<p>Express comes with a built-in error handler, which takes care of any remaining errors that might be encountered in the app. This default error-handling middleware function is added at the end of the middleware function stack. If you pass an error to <code>next()</code> and you do not handle it in an error handler, it will be handled by the built-in error handler; the error will be written to the client with the stack trace.</p> + +<div class="note"> +<p><strong>Note:</strong> The stack trace is not included in the production environment. To run it in production mode you need to set the the environment variable <code>NODE_ENV</code> to '<code>production'</code>.</p> +</div> + +<div class="note"> +<p><strong>Note:</strong> HTTP404 and other "error" status codes are not treated as errors. If you want to handle these, you can add a middleware function to do so. For more information see the <a href="http://expressjs.com/en/starter/faq.html#how-do-i-handle-404-responses">FAQ</a>.</p> +</div> + +<p>For more information see <a href="http://expressjs.com/en/guide/error-handling.html">Error handling</a> (Express docs).</p> + +<h3 id="Using_databases">Using databases</h3> + +<p><em>Express</em> apps can use any database mechanism supported by <em>Node</em> (<em>Express</em> itself doesn't define any specific additional behaviour/requirements for database management). There are many options, including PostgreSQL, MySQL, Redis, SQLite, MongoDB, etc.</p> + +<p>In order to use these you have to first install the database driver using NPM. For example, to install the driver for the popular NoSQL MongoDB you would use the command:</p> + +<pre class="brush: bash"><code>$ npm install mongodb +</code></pre> + +<p>The database itself can be installed locally or on a cloud server. In your Express code you require the driver, connect to the database, and then perform create, read, update, and delete (CRUD) operations. The example below (from the Express documentation) shows how you can find "mammal" records using MongoDB.</p> + +<pre class="brush: js">//this works with older versions of mongodb version ~ 2.2.33 +var MongoClient = require('mongodb').MongoClient; + +MongoClient.connect('mongodb://localhost:27017/animals', function(err, db) { + if (err) throw err; + + db.collection('mammals').find().toArray(function (err, result) { + if (err) throw err; + + console.log(result); + }); +}); + + +//for mongodb version 3.0 and up +let MongoClient = require('mongodb').MongoClient; +MongoClient.connect('mongodb://localhost:27017/animals', function(err, client){ + if(err) throw err; + + let db = client.db('animals'); + db.collection('mammals').find().toArray(function(err, result){ + if(err) throw err; + console.log(result); + client.close(); + }); +} +</pre> + + + + + + + +<p>Another popular approach is to access your database indirectly, via an Object Relational Mapper ("ORM"). In this approach you define your data as "objects" or "models" and the ORM maps these through to the underlying database format. This approach has the benefit that as a developer you can continue to think in terms of JavaScript objects rather than database semantics, and that there is an obvious place to perform validation and checking of incoming data. We'll talk more about databases in a later article.</p> + +<p>For more information see <a href="https://expressjs.com/en/guide/database-integration.html">Database integration</a> (Express docs).</p> + +<h3 id="Rendering_data_(views)">Rendering data (views)</h3> + +<p>Template engines (referred to as "view engines" by <em>Express</em>) allow you to specify the <em>structure</em> of an output document in a template, using placeholders for data that will be filled in when a page is generated. Templates are often used to create HTML, but can also create other types of documents. Express has support for <a href="https://github.com/expressjs/express/wiki#template-engines">a number of template engines</a>, and there is a useful comparison of the more popular engines here: <a href="https://strongloop.com/strongblog/compare-javascript-templates-jade-mustache-dust/">Comparing JavaScript Templating Engines: Jade, Mustache, Dust and More</a>.</p> + +<p>In your application settings code you set the template engine to use and the location where Express should look for templates using the 'views' and 'view engines' settings, as shown below (you will also have to install the package containing your template library too!)</p> + +<pre class="brush: js">var express = require('express'); +var app = express(); + +// Set directory to contain the templates ('views') +app.set('views', path.join(__dirname, 'views')); + +// Set view engine to use, in this case 'some_template_engine_name' +app.set('view engine', 'some_template_engine_name'); +</pre> + +<p>The appearance of the template will depend on what engine you use. Assuming that you have a template file named "index.<template_extension>" that contains placeholders for data variables named 'title' and "message", you would call <code><a href="http://expressjs.com/en/4x/api.html#res.render">Response.render()</a></code> in a route handler function to create and send the HTML response:</p> + +<pre class="brush: js">app.get('/', function(req, res) { + res.render('index', { title: 'About dogs', message: 'Dogs rock!' }); +});</pre> + +<p>For more information see <a href="http://expressjs.com/en/guide/using-template-engines.html">Using template engines with Express</a> (Express docs).</p> + +<h3 id="File_structure">File structure</h3> + +<p>Express makes no assumptions in terms of structure or what components you use. Routes, views, static files, and other application-specific logic can live in any number of files with any directory structure. While it is perfectly possible to have the whole <em>Express</em> application in one file, typically it makes sense to split your application into files based on function (e.g. account management, blogs, discussion boards) and architectural problem domain (e.g. model, view or controller if you happen to be using an <a href="/en-US/docs/Web/Apps/Fundamentals/Modern_web_app_architecture/MVC_architecture">MVC architecture</a>).</p> + +<p>In a later topic we'll use the <em>Express Application Generator</em>, which creates a modular app skeleton that we can easily extend for creating web applications.</p> + +<ul> +</ul> + +<h2 id="總結">總結</h2> + +<p>恭喜,您已完成 Express / Node之旅的第一步!您現在應該了解 Express 和 Node 的主要優點,以及 Express 應用程序的主要部分(路由,中間件,錯誤處理和模板代碼)。您還應該明白,Express 是一個不固執己見的框架,您將這些組件組合在一起的方式以及您使用的函式庫,在很大程度上取決於您!</p> + +<p>當然,Express是一個非常輕量級的 Web 應用程序框架,它的許多好處和潛力來自第三方函式庫和功能。我們將在以下文章中更詳細地介紹這些內容。在下一篇文章中,我們將介紹如何設置 Node 開發環境,以便您可以開始查看一些 Express 代碼。</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="https://medium.com/@ramsunvtech/manage-multiple-node-versions-e3245d5ede44">Venkat.R - Manage Multiple Node versions</a></li> + <li><a href="https://nodejs.org/api/modules.html#modules_modules">Modules</a> (Node API docs)</li> + <li><a href="https://expressjs.com/">Express</a> (home page)</li> + <li><a href="http://expressjs.com/en/starter/basic-routing.html">Basic routing</a> (Express docs)</li> + <li><a href="http://expressjs.com/en/guide/routing.html">Routing guide</a> (Express docs)</li> + <li><a href="http://expressjs.com/en/guide/using-template-engines.html">Using template engines with Express</a> (Express docs)</li> + <li><a href="https://expressjs.com/en/guide/using-middleware.html">Using middleware</a> (Express docs)</li> + <li><a href="http://expressjs.com/en/guide/writing-middleware.html">Writing middleware for use in Express apps</a> (Express docs)</li> + <li><a href="https://expressjs.com/en/guide/database-integration.html">Database integration</a> (Express docs)</li> + <li><a href="http://expressjs.com/en/starter/static-files.html">Serving static files in Express</a> (Express docs)</li> + <li><a href="http://expressjs.com/en/guide/error-handling.html">Error handling</a> (Express docs)</li> +</ul> + +<div>{{NextMenu("Learn/Server-side/Express_Nodejs/development_environment", "Learn/Server-side/Express_Nodejs")}}</div> + +<h2 id="In_this_module">In this module</h2> + +<ul> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node introduction</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">Setting up a Node (Express) development environment</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Express Tutorial: The Local Library website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Express Tutorial Part 2: Creating a skeleton website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Express Tutorial Part 3: Using a Database (with Mongoose)</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/routes">Express Tutorial Part 4: Routes and controllers</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/deployment">Express Tutorial Part 7: Deploying to production</a></li> +</ul> diff --git a/files/zh-tw/learn/server-side/express_nodejs/mongoose/index.html b/files/zh-tw/learn/server-side/express_nodejs/mongoose/index.html new file mode 100644 index 0000000000..8541c1c37c --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/mongoose/index.html @@ -0,0 +1,792 @@ +--- +title: 'Express 教學 3: 使用資料庫 ( Mongoose)' +slug: Learn/Server-side/Express_Nodejs/mongoose +translation_of: Learn/Server-side/Express_Nodejs/mongoose +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/skeleton_website", "Learn/Server-side/Express_Nodejs/routes", "Learn/Server-side/Express_Nodejs")}}</div> + +<p class="summary">本文簡短介紹數據庫,以及如何搭配 Node / Express 應用,使用數據庫。接下來會演示我們如何使用 <a href="http://mongoosejs.com/">Mongoose</a>,為本地圖書館提供數據庫存取。本文說明物件要求與模型如何宣告,主要的欄位型態,以及基本驗證。本文也簡短演示一些存取模型數據的主要方法。</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">前置條件:</th> + <td><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Express 教學 2: 創建一個骨架網站</a></td> + </tr> + <tr> + <th scope="row">目標:</th> + <td>能夠使用Mongoose設計並創造自己的模型。</td> + </tr> + </tbody> +</table> + +<h2 id="概覽">概覽</h2> + +<p>圖書館職員會使用本地圖書館網站,存放書本和借書者<font><font>訊息</font></font>。圖書館使用者會用網站瀏覽與尋找書本,看看是否有可以藉閱的書本複本,然後預約或者藉閱。為了有效率地存放與取用<font><font>訊息</font></font>,我們將把它存放到數據庫。</p> + +<p>Express 應用可以使用許多不同的數據庫,並且有好幾種方法可以執行創建 <strong>C</strong>reate、讀取 <strong>R</strong>ead、更新 <strong>U</strong>pdate 和刪除 <strong>D</strong>elete (CRUD) 操作。本教程為一些可用的選項,提供簡短的概覽,然後接著詳細演示該選項的特定運行機制。</p> + +<h3 id="我可以使用什麼數據庫">我可以使用什麼數據庫?</h3> + +<p>Express 應用程序可以使用 Node 支持的任何數據庫(Express 本身不會為數據庫管理,定義任何特定的附加行為/要求)。有許多<a href="https://expressjs.com/en/guide/database-integration.html">流行的選項</a>,包括 PostgreSQL,MySQL,Redis,SQLite 和 MongoDB。</p> + +<p>在選擇數據庫時,您應該考慮時間 - 生產力/學習曲線,性能,易複製/備份,成本,社區支持等等。雖然沒有單一的 “最佳” 數據庫,但幾乎任何流行的解決方案,我們的本地圖書館這樣的中小型網站,應該都可以接受。</p> + +<p>有關選項的更多<font><font>訊息</font></font>,請參閱:<a href="https://expressjs.com/en/guide/database-integration.html">數據庫集成(Express docs)</a>。</p> + +<h3 id="與數據庫互動的最好方式是什麼">與數據庫互動的最好方式是什麼?</h3> + +<p>有兩種與數據庫互動的方法:</p> + +<ul> + <li>使用數據庫的原生查詢語言(例如SQL)</li> + <li>使用對像數據模型(“ODM”)/對象關係模型(“ORM”)。 ODM / ORM將網站的數據表示為JavaScript對象,然後將其映射到底層數據庫。一些ORM綁定到特定的數據庫,而另一些則提供了一個不特定數據庫的後端。</li> +</ul> + +<p>通過使用 SQL 或數據庫支持的任何查詢語言,都可以獲得最佳性能。 ODM通常比較慢,因為它們使用翻譯代碼,在對象和數據庫格式之間進行映射,這可能不會使用最有效的數據庫查詢(尤其是如果ODM支持不同的數據庫後端,並且必須在各個數據庫所支持的功能方面,做出更大的折衷)。</p> + +<p>使用 ORM 的好處是,程序員可以繼續用 JavaScript 對象而不是數據庫語義來思考 — 如果您需要使用不同數據庫(在相同或不同的網站上),那麼尤其如此。他們還提供了一個明顯的地方來執行數據驗證和檢查。</p> + +<div class="note"> +<p><strong>提示:</strong> 使用ODM / ORM通常可以降低開發和維護成本!除非您非常熟悉本地查詢語言,或者性能對您至關重要,否則您應該強烈考慮使用 ODM。</p> +</div> + +<h3 id="我應該使用哪個_ORMODM">我應該使用哪個 ORM/ODM ?</h3> + +<p>NPM 套件管理器站點上,有許多ODM / ORM 解決方案(查看 <a href="https://www.npmjs.com/browse/keyword/odm">odm</a> 和 <a href="https://www.npmjs.com/browse/keyword/orm">orm</a> 標籤的子集合!)。</p> + +<p>在撰寫本文時,受歡迎的幾種解決方案是: </p> + +<ul> + <li><a href="https://www.npmjs.com/package/mongoose">Mongoose</a>: Mongoose 是一個 <a href="https://www.mongodb.org/">MongoDB</a>對象建模工具,用於在異步環境中工作。</li> + <li><a href="https://www.npmjs.com/package/waterline">Waterline</a>: 它是從基於Express的 Sails web 框架中提取的 ORM。它提供了一個統一的 API,來訪問眾多不同的數據庫,包括Redis,mySQL,LDAP,MongoDB 和 Postgres。</li> + <li><a href="https://www.npmjs.com/package/bookshelf">Bookshelf</a>: 提供基於 promise 和傳統回調的接口,提供事務支持,eager/嵌套 eager 關係加載,多態關聯以及對一對一,一對多和多對多關係的支持。適用於PostgreSQL,MySQL 和 SQLite3。</li> + <li><a href="https://www.npmjs.com/package/objection">Objection</a>: 以盡可能簡單的方式,使用 SQL 的全部功能,和底層數據庫引擎(支持SQLite3,Postgres 和 MySQL)。</li> + <li> + <p><a href="https://www.npmjs.com/package/sequelize">Sequelize</a> 是 Node.js 和 io.js 基於 promise 的 ORM。它支持以下數據庫方言,PostgreSQL,MySQL,MariaDB,SQLite 和 MSSQL,並具有可靠的事務支持,關係,唯讀複本等功能。</p> + </li> +</ul> + +<p>一般來說,在選擇解決方案時,您應該考慮提供的功能和 “社區活動” (下載,貢獻,錯誤報告,文檔質量等)。在撰寫本文時,Mongoose 是迄今為止最受歡迎的 ODM,如果您將MongoDB 用於你的數據庫,那麼它是一個合理的選擇。</p> + +<h3 id="在本地圖書館使用_Mongoose_和_MongoDb">在本地圖書館使用 Mongoose 和 MongoDb</h3> + +<p>對於本地圖書館示例(以及本主題的其餘部分),我們將使用 <a href="https://www.npmjs.com/package/mongoose">Mongoose ODM </a>來訪問我們的圖書館數據。 Mongoose 是 <a href="https://www.mongodb.com/what-is-mongodb">MongoDB</a> 的前端,MongoDB 是一個使用面向文檔數據模型的開源 <a href="https://en.wikipedia.org/wiki/NoSQL">NoSQL</a> 數據庫。在 MongoDB 數據庫中,“文檔” 的 “集合” ,<a href="https://docs.mongodb.com/manual/core/databases-and-collections/#collections">類似於</a>關係數據庫中 “行” 的 “表”。</p> + +<p>這種 ODM 和數據庫的結合在 Node 社區中非常流行,部分原因是文檔存儲和查詢系統,看起來非常像 JSON,因此對 JavaScript 開發人員來說很熟悉。</p> + +<div class="note"> +<p><strong>提示:</strong> 使用 Mongoose 時,您不需要事先了解 MongoDB,但是如果您已經熟悉 MongoDB,<a href="http://mongoosejs.com/docs/guide.html">Mongoose documentation </a>文檔的一部分會更易於使用和理解。</p> +</div> + +<p>本教程的其餘部分,將介紹如何為 本地圖書館網站示例,定義和訪問Mongoose 模式和模型。</p> + +<h2 id="設計本地圖書館的模型"><font><font>設計本地圖書館的模型</font></font></h2> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>在您開始編寫模型之前,花幾分鐘的時間思考,我們需要儲存的數據以及不同對象之間的關係。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>我們知道,我們需要儲存有關書籍的訊息(標題,摘要,作者,種類,國際標準書號),以及我們可能有多個副本可用(具有全域唯一ID,可用狀態等)。我們可能需要存儲有關作者的更多訊息,而不僅僅是他們的名字,並且可能有多個作者,具有相同或相似的名稱。我們希望能夠根據書名,作者,種類和類別對訊息進行分類。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>在設計模型時,對於每個“對象”(相關訊息組)都有獨立的模型,是有意義的。在這種情況下,明顯的對像是書籍,書籍實例和作者。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>您可能還希望,使用模型來表示選擇列表選項(例如,選擇的下拉列表),而不是將選項硬編碼到網站本身— 在無法預先知道所有選項,或者可能更改時,更建議使用模型來表示。</font><font>很明顯的,書本類型是這種模型的可能人選(例如科幻小說,法國詩歌等)。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>一旦我們決定了我們的模型和字段,我們就需要考慮它們之間的關係。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>考慮到這一點,下面的UML關聯圖,顯示了我們在這種情況下定義的模型(一個框對應一個模型)。</font><font>如上所述,我們創建了以下模型,圖書(本書的通用細節),書本實例(系統中可用圖書的特定實際副本的狀態)和作者。</font><font>我們還決定建立一個種類模型,以便可以動態創建它的值,而不是將下拉選項硬編碼。</font><font>我們已經決定不為書本實例:狀態</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>BookInstance:status</code><font><font>建立模型—我們將硬編碼可接受的值,因為我們不希望這些值發生變化。</font><font>在下圖每個框中,您可以看到模型名稱,字段名稱和類型,以及方法及其返回類型。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>下圖還顯示了模型之間的關係,包括它們的多重性。</font><font>多重性是圖中顯示可能存在於關係中的每個模型的數量(最大值和最小值)的數字。</font><font>例如,框之間的連接線,顯示書本</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>Book</code><font><font>和種類</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>Genre</code><font><font>是相關的。</font><font>靠近書本</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>Book</code><font><font>模型的數字,表明一本書必須有零個或多個種類(您想要多少都可以),而種類</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>Genre</code><font><font>旁邊一行的數字,表明它可以有零個或多個相關書籍。</font></font></p> + +<div class="note"> +<p><strong>注意</strong>: <font><font>正如我們在下面的</font></font><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>Mongoose入門</font></font></strong><font><font>中所討論的那樣,通常只需要在一個模型中定義文檔/模型之間關係的字段(通過在另一個模型中搜索相關的</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>_id</code><font><font>仍然可以找到反向關係)。</font><font>下面我們選擇在書本綱要(Book schema)中定義Book/Genre和Book/Author之間的關係,以及書本實例綱要(BookInstance Schema)中Book/BookInstance之間的關係。</font><font>這種選擇有點武斷—我們同樣可以在其他綱要中擁有該字段。</font></font></p> +</div> + +<p><img alt="Mongoose Library Model with correct cardinality" src="https://mdn.mozillademos.org/files/15645/Library%20Website%20-%20Mongoose_Express.png" style="height: 620px; width: 737px;"></p> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>注意</font></font></strong><font><font><span> </span>:下一節提供了一個基本的入門知識,解釋如何定義和使用模型。</font><font>在您閱讀它時,請想想我們將如何構建上圖中的每個模型。</font></font></p> +</div> + +<h2 id="Mongoose入門"><font><font>Mongoose入門</font></font></h2> + +<p><span style='background-color: #ffffff; color: #333333; display: inline !important; float: none; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; font-weight: 400; letter-spacing: normal; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'>本節概述如何將Mongoose 連接到MongoDB 數據庫,如何定義模型綱要和模型,以及如何進行基本查詢。</span></p> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>注意:</font></font></strong><font><font>本入門受到npm上的</font></font><a class="external external-icon" href="https://www.npmjs.com/package/mongoose" rel="noopener" style='font-style: normal; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 18px; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; background-color: rgb(255, 243, 212);'><font><font>Mongoose快速入門</font></font></a><font><font>和</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/guide.html" rel="noopener" style='font-style: normal; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 18px; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; background-color: rgb(255, 243, 212);'><font><font>Mongoose官方文檔</font></font></a><font><font>的“深度影響”。</font></font></p> +</div> + +<h3 id="安裝Mongoose和MongoDB"><span class="highlight-span" style="background-color: #333333; border: 0px; color: #ffffff; font-style: normal !important; font-weight: 400; line-height: 1.25; margin: 0px; padding: 0px 4px 0px 40px;"><font><font>安裝Mongoose和MongoDB</font></font></span></h3> + +<p><font><font>Mongoose像任何其他依賴項一樣,安裝在您的項目(</font></font><strong style='background-color: #ffffff; border: 0px; color: #333333; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>package.json</font></font></strong><font><font>)中—使用NPM。</font><font>要安裝它,請在項目文件夾中,使用以下命令:</font></font></p> + +<pre class="brush: bash notranslate"><code>npm install mongoose</code> +</pre> + +<p><font><font>安裝Mongoose會添加所有依賴項,包括MongoDB數據庫驅動程序,但它不會安裝MongoDB 。</font><font>如果你想安裝一個MongoDB服務器,那麼你可以</font></font><a class="external external-icon" href="https://www.mongodb.com/download-center" rel="noopener" style='font-style: normal; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line; font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; background-color: rgb(255, 255, 255);'><font><font>從這裡下載</font></font></a><font><font>各種操作系統的安裝程序,並在本地安裝。</font><font>您還可以使用基於雲端的MongoDB實例。</font></font></p> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>注意:</font></font></strong><font><font>對於本教程,我們將使用基於mLab雲的數據庫,作為服務</font></font><a class="external external-icon" href="https://mlab.com/plans/pricing/" rel="noopener" style='font-style: normal; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 18px; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; background-color: rgb(255, 243, 212);'><font><font>沙箱層</font></font></a><font><font>來提供數據庫。</font><font>這適用於開發,也對於本教程很有意義,因為它使“安裝”與操作系統無關(數據庫即服務,也是您可能會用於生產環境數據庫的一種方法)。</font></font></p> +</div> + +<h3 id="連接到MongoDB"><span class="highlight-span" style="background-color: #333333; border: 0px; color: #ffffff; font-style: normal !important; font-weight: 400; line-height: 1.25; margin: 0px; padding: 0px 4px 0px 40px;"><font><font>連接到MongoDB</font></font></span></h3> + +<p><font><font>Mongoose需要連接到MongoDB數據庫。</font><font>您可以</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>require()</code><font><font>並使用</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>mongoose.connect()</code><font><font>,以連接到本地託管的數據庫,如下所示。</font></font></p> + +<pre class="brush: js notranslate">//Import the mongoose module +var mongoose = require('mongoose'); + +//Set up default mongoose connection +var mongoDB = 'mongodb://127.0.0.1/my_database'; +mongoose.connect(mongoDB); +// Get Mongoose to use the global promise library +mongoose.Promise = global.Promise; +//Get the default connection +var db = mongoose.connection; + +//Bind connection to error event (to get notification of connection errors) +db.on('error', console.error.bind(console, 'MongoDB connection error:'));</pre> + +<p><font><font>您可以使用</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>mongoose.connection</code><font><font>獲取默認的</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>Connection</code><font><font>對象。</font><font>一旦連接,在</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>Connection</code><font><font>實例上,將觸發打開事件。</font></font></p> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>提示:</font></font></strong><font><font>如果需要創建其他連接,可以使用</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>mongoose.createConnection()</code><font><font>。</font><font>這與</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>connect()</code><font><font>採用相同形式的數據庫URI(包含主機,數據庫,端口,選項等),並返回</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>Connection</code><font><font>對象。</font></font></p> +</div> + +<h3 id="定義並創建模型"><span class="highlight-span" style="background-color: #333333; border: 0px; color: #ffffff; font-style: normal !important; font-weight: 400; line-height: 1.25; margin: 0px; padding: 0px 4px 0px 40px;"><font><font>定義並創建模型</font></font></span></h3> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>模型使用</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>Schema</code><font><font>接口進行定義。</font><font>Schema允許您定義存儲在每個文檔中的字段,及其驗證要求和默認值。</font><font>此外,您可以定義靜態和實例助手方法,以更輕鬆地處理數據類型,以及可以像其他任何字段一樣使用的虛擬屬性,但實際上並不存儲在數據庫中(我們稍後將討論)。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>然後,綱要Schemas被</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>mongoose.model()</code><font><font>方法“編譯”為模型。</font><font>擁有模型後,您可以使用它來查找,創建,更新和刪除給定類型的對象。</font></font></p> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>注意:</font></font></strong><font><font>每個模型都映射到MongoDB數據庫中的文檔集合。</font><font>這些文檔將包含模型綱要</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>Schema</code><font><font>中定義的字段/綱要型態。</font></font></p> +</div> + +<h4 id="定義綱要Schemas" style='font-style: normal; line-height: 1.2; margin: 30px 0px 20px; padding: 0px; border: 0px; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 1.375rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>定義綱要Schemas</font></font></h4> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>下面的代碼片段,顯示了您可以如何定義一個簡單的綱要。</font><font>首先</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>require()</code><font><font>mongoose,然後使用Schema構造函數,創建一個新的Schema實例,在構造函數的對象參數中,定義其中的各個字段。</font></font></p> + +<pre class="brush: js notranslate">//Require Mongoose +var mongoose = require('mongoose'); + +//Define a schema +var Schema = mongoose.Schema; + +var SomeModelSchema = new Schema({ + a_string: String, + a_date: Date +}); +</pre> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>在上面的例子中,我們只有兩個字段,一個字符串和一個日期。</font><font>在接下來的部分中,我們將展示一些其他的字段類型,驗證和其他方法。</font></font></p> + +<h4 id="創建模型" style='font-style: normal; line-height: 1.2; margin: 30px 0px 20px; padding: 0px; border: 0px; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 1.375rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>創建模型</font></font></h4> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>使用</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>mongoose.model()</code><font><font>方法從綱要創建模型:</font></font></p> + +<pre class="brush: js notranslate">// Define schema +var Schema = mongoose.Schema; + +var SomeModelSchema = new Schema({ + a_string: String, + a_date: Date +}); + +<strong>// Compile model from schema +var SomeModel = mongoose.model('SomeModel', SomeModelSchema );</strong></pre> + +<p><span style='background-color: #ffffff; color: #333333; display: inline !important; float: none; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; font-weight: 400; letter-spacing: normal; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'>第一個參數,是將為模型創建的集合的單數名稱(Mongoose將為上面的SomeModel模型,創建數據庫集合),第二個參數,是您要在創建模型時使用的綱要Shema。</span></p> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>注意:</font></font></strong><font><font>定義模型類後,可以使用它們來創建,更新或刪除記錄,並運行查詢,以獲取記錄的所有記錄,或特定子集。</font><font>我們將在以下“使用模型”部分,向您展示如何執行上述操作,以及當創建視圖時,如何執行此操作。</font></font></p> +</div> + +<h4 id="綱要型態(字段)" style='font-style: normal; line-height: 1.2; margin: 30px 0px 20px; padding: 0px; border: 0px; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 1.375rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>綱要型態(字段)</font></font></h4> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>綱要schema可以有任意數量的字段 — 每個字段代表存儲在MongoDB 文檔中的字段。</font><font>如下的示例綱要,顯示許多常見字段類型及其聲明方式。</font></font></p> + +<pre class="brush: js notranslate">var schema = new Schema( +{ + name: <strong>String</strong>, + binary: <strong>Buffer</strong>, + living: <strong>Boolean</strong>, + updated: { type: <strong>Date</strong>, default: Date.now }, + age: { type: <strong>Number</strong>, min: 18, max: 65, required: true }, + mixed: <strong>Schema.Types.Mixed</strong>, + _someId: <strong>Schema.Types.ObjectId</strong>, + array: <strong>[]</strong>, + ofString: [<strong>String</strong>], // You can also have an array of each of the other types too. + nested: { stuff: { type: <strong>String</strong>, lowercase: true, trim: true } } +})</pre> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>大多數綱要型態</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/schematypes.html" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>SchemaTypes</font></font></a><font><font>(“type:”之後或字段名稱之後的描述符)都是自解釋的。</font><font>例外情況是:</font></font></p> + +<ul style='font-style: normal; margin: 0px 0px 24px; padding: 0px 0px 0px 40px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>ObjectId</code><font><font>:表示數據庫中模型的特定實例。</font><font>例如,一本書可能會使用它來表示其作者對象。</font><font>這實際上將包含指定對象的唯一ID (<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>_id</code><font><font>) 。</font><font>我們可以使用</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>populate()</code><font><font>方法,在需要時提取相關訊息。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><a class="external external-icon" href="http://mongoosejs.com/docs/schematypes.html#mixed" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>Mixed</font></font></a><font><font><span> </span>:任意綱要型態。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font face="Consolas, Liberation Mono, Courier, monospace"><font><font>[]</font></font></font><font><font><span> </span>:一個數組的項目。</font><font>您可以在這些模型上執行JavaScript數組操作(push,pop,unshift等)。</font><font>上面的例子,顯示了一個沒有指定類型的對像數組,和一個String對像數組,但是你可以有任何類型的對像數組。</font></font></li> +</ul> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>該代碼還顯示了聲明一個字段的兩種方式:</font></font></p> + +<ul style='font-style: normal; margin: 0px 0px 24px; padding: 0px 0px 0px 40px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>字段名稱和類型作為鍵值對(即是,像上面的</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>name</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>binary<span> </span></code><font><font>and<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>living</code><font><font>)。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>字段名稱後跟一個定義類型</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>type</code><font><font>的對象,以及該字段的任何其他選項。</font><font>選項包括如下內容:</font></font> + <ul style="font-style: normal !important; margin: 0px; padding: 6px 0px 0px 40px; border: 0px; max-width: 42rem;"> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>默認值。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>內置驗證器(例如最大/最小值)和自定義驗證功能。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>該字段是否為必要</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>是否應將字符串</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>String</code><font><font>字段自動設置為小寫,大寫或修剪(例如</font><font>)</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>{ type:<strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;">String</strong>, lowercase: true, trim: true }</code></li> + </ul> + </li> +</ul> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>有關選項的更多訊息,請參閱</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/schematypes.html" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>SchemaTypes</font></font></a><font><font>(Mongoose docs)。</font></font></p> + +<h4 id="驗證" style='font-style: normal; line-height: 1.2; margin: 30px 0px 20px; padding: 0px; border: 0px; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 1.375rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>驗證</font></font></h4> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>Mongoose 提供內置和自定義驗證器,以及同步和異步驗證器。</font><font>它允許您在所有情況下,指定可接受的範圍或值,以及驗證失敗的錯誤消息。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>內置的驗證器包括:</font></font></p> + +<ul style='font-style: normal; margin: 0px 0px 24px; padding: 0px 0px 0px 40px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>所有</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/schematypes.html" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>SchemaTypes</font></font></a><font><font>都具有內置的</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#schematype_SchemaType-required" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>必需</font></font></a><font><font>驗證器。</font><font>這用於指定,是否必須提供該字段才能保存文檔。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#schema-number-js" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>Numbers </font></font></a><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#schema-number-js" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>數字</font></font></a><font><font>有最小</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#schema_number_SchemaNumber-min" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>min</font></font></a><font><font>和最大</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#schema_number_SchemaNumber-max" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>max</font></font></a><font><font>驗證器。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#schema-string-js" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>Strings</font></font></a><font><font>字符串有:</font></font> + <ul style="font-style: normal !important; margin: 0px; padding: 6px 0px 0px 40px; border: 0px; max-width: 42rem;"> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#schema_string_SchemaString-enum" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>enum</font></font></a><font><font>枚舉:指定該字段的允許值集合。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#schema_string_SchemaString-match" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>match</font></font></a><font><font><span> </span>:指定字符串必須匹配的正則表達式。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>字符串的最大長度</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#schema_string_SchemaString-maxlength" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>maxlength</font></font></a><font><font>和最小長度</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#schema_string_SchemaString-minlength" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>minlength</font></font></a></li> + </ul> + </li> +</ul> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>下面的示例(從Mongoose文檔稍微修改)顯示瞭如何指定一些驗證器類型和錯誤消息:</font></font></p> + +<pre class="brush: js notranslate"><code> + var breakfastSchema = new Schema({ + eggs: { + type: Number, + min: [6, 'Too few eggs'], + max: 12 + required: [true, 'Why no eggs?'] + }, + drink: { + type: String, + enum: ['Coffee', 'Tea', 'Water',] + } + }); +</code></pre> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>有關字段驗證的完整訊息,請參閱</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/validation.html" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>驗證</font></font></a><font><font>(Mongoose docs)。</font></font></p> + +<h4 id="虛擬屬性" style='font-style: normal; line-height: 1.2; margin: 30px 0px 20px; padding: 0px; border: 0px; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 1.375rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>虛擬屬性</font></font></h4> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>虛擬屬性是您可以獲取和設置的文檔屬性,但不會持久保存到MongoDB。</font><font>getter 對格式化或組合字段非常有用,而setter 可用於將單個值分解為多個值,以進行存儲。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>文檔中的示例,從名字和姓氏字段構造(並解構)一個全名虛擬屬性,這比每次在模板中使用全名更簡單,更清晰。</font></font></p> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>注意:</font></font></strong><font><font>我們將使用庫中的虛擬屬性,來為每個使用路徑和記錄的<code>_id</code>值的模型記錄,定義唯一的URL。</font></font></p> +</div> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>欲了解更多訊息,請參閱</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/guide.html#virtuals" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>虛擬</font></font></a><font><font>(Mongoose文檔)。</font></font></p> + +<h4 id="方法和查詢幫助" style='font-style: normal; line-height: 1.2; margin: 30px 0px 20px; padding: 0px; border: 0px; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 1.375rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>方法和查詢幫助</font></font></h4> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>綱要schema也可以有</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/guide.html#methods" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>實例方法</font></font></a><font><font>,</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/guide.html#statics" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>靜態方法</font></font></a><font><font>和</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/guide.html#query-helpers" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>查詢助手</font></font></a><font><font>。</font><font>實例和靜態方法很相似,但有明顯的區別,即實例方法與特定記錄相關聯,並且可以訪問當前對象。</font><font>查詢助手允許您擴展mongoose的</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/queries.html" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>鍊式查詢構建器API</font></font></a><font><font>(例如,除了</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>find()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>findOne()</code><font><font>和</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>findById()</code><font><font>方法外,還允許您添加一個“byName”查詢。</font></font></p> + +<h3 id="使用模型"><span class="highlight-span" style="background-color: #333333; border: 0px; color: #ffffff; font-style: normal !important; font-weight: 400; line-height: 1.25; margin: 0px; padding: 0px 4px 0px 40px;"><font><font>使用模型</font></font></span></h3> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>一旦創建了綱要,就可以使用它來創建模型。</font><font>該模型代表數據庫中可以搜索的文檔集合,而模型的實例代表您可以保存和檢索的單個文檔。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>我們在下面簡要介紹一下。有關更多訊息,請參閱:</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/models.html" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>模型</font></font></a><font><font>(Mongoose docs)。</font></font></p> + +<h4 id="創建和修改文檔" style='font-style: normal; line-height: 1.2; margin: 30px 0px 20px; padding: 0px; border: 0px; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 1.375rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>創建和修改文檔</font></font></h4> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>要創建記錄,您可以定義模型的實例,然後調用</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>save()</code><font><font>。</font><font>下面的例子假設,SomeModel是我們從綱要創建的模型(帶有單一字段“name” )。</font></font></p> + +<pre class="brush: js notranslate"><code>// Create an instance of model SomeModel +var awesome_instance = new </code>SomeModel<code>({ name: 'awesome' }); + +// Save the new model instance, passing a callback +awesome_instance.save(function (err) { + if (err) return handleError(err); + // saved! +}); +</code></pre> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>創建記錄(以及更新,刪除和查詢)是異步操作— 您提供在操作完成時調用的回調。</font><font>API使用錯誤優先參數約定,因此回調的第一個參數將始終為錯誤值(或null)。</font><font>如果API返回一些結果,則將作為第二個參數提供。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>您還可以使用</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>create()</code><font><font>,同時定義模型實例,並保存模型實例。</font><font>回調將為第一個參數返回錯誤,為第二個參數返回新創建的模型實例。</font></font></p> + +<pre class="brush: js notranslate">SomeModel<code>.create({ name: 'also_awesome' }, function (err, awesome_instance) { + if (err) return handleError(err); + // saved! +});</code></pre> + +<p><font><font>每個模型都有一個關聯的連接(當您使用</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>mongoose.model()</code><font><font>時,這將成為默認連接)。</font><font>您創建一個新連接並調用</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>.model()</code><font><font>,以在另一個數據庫上創建文檔。</font></font></p> + +<p><font><font>您可以使用點語法訪問此新記錄中的字段,並更改值。</font><font>您必須調用</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>save()</code><font><font>或</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>update()</code><font><font>,將修改的值存回數據庫。</font></font></p> + +<pre class="brush: js notranslate">// Access model field values using dot notation +console.log(<code>awesome_instance.name</code>); //should log '<code>also_awesome</code>' + +// Change record by modifying the fields, then calling save(). +<code>awesome_instance</code>.name="New cool name"; +<code>awesome_instance.save(function (err) { + if (err) return handleError(err); // saved! + });</code> +</pre> + +<h4 id="尋找紀錄" style='font-style: normal; line-height: 1.2; margin: 30px 0px 20px; padding: 0px; border: 0px; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 1.375rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>尋找紀錄</font></font></h4> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>可以使用查詢方法搜索記錄,將查詢條件指定為JSON 文檔。</font><font>下面的代碼片段,顯示瞭如何在數據庫中,找到所有參加網球運動的運動員,只返回運動員姓名和年齡的字段。</font><font>這裡我們只指定一個匹配的字段(運動 sport),但您可以添加更多條件,指定正則表達式標準,或完全刪除條件以返回所有運動員。</font></font></p> + +<pre class="brush: js notranslate"><code>var Athlete = mongoose.model('Athlete', yourSchema); + +// find all athletes who play tennis, selecting the 'name' and 'age' fields +Athlete.find({ 'sport': 'Tennis' }, 'name age', function (err, athletes) { + if (err) return handleError(err); + // 'athletes' contains the list of athletes that match the criteria. +})</code></pre> + +<p><font>如果您指定回調,如上所示,查詢將立即執行。</font><font>搜索完成後將調用回調。</font></p> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>注意:</font></font></strong><font><font><span> </span>Mongoose中的所有回調,都使用此回調模式</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>callback(error, result)</code><font><font>。</font><font>如果執行查詢時發生錯誤,錯誤參數</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>error</code><font><font>將包含錯誤文檔,並且結果</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>result</code><font><font>將為null。</font><font>如果查詢成功,則</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>error</code><font><font>參數將為null,並且結果</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>result<span> </span></code><font><font>將被填充到查詢結果。</font></font></p> +</div> + +<p><font><font>如果您未指定回調,則API將返回</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#query-js" rel="noopener" style='font-style: normal; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line; font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; background-color: rgb(255, 255, 255);'><font><font>Query</font></font></a><font><font>類型的變量。</font><font>您可以使用此查詢對象來構建查詢,然後稍後使用</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>exec()</code><font><font>方法執行(使用回調)。</font></font></p> + +<pre class="brush: js notranslate"><code>// find all athletes that play tennis +var query = Athlete.find({ 'sport': 'Tennis' }); + +// selecting the 'name' and 'age' fields +query.select('name age'); + +// limit our results to 5 items +query.limit(5); + +// sort by age +query.sort({ age: -1 }); + +// execute the query at a later time +query.exec(function (err, athletes) { + if (err) return handleError(err); + // athletes contains an ordered list of 5 athletes who play Tennis +})</code></pre> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>上面我們在</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>find()</code><font><font>方法中,定義了查詢條件。</font><font>我們也可以使用</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>where()</code><font><font>函數來執行此操作,並且我們可以使用點運算符( . )將查詢的所有部分鏈接在一起,而不是分別添加它們。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>下面的代碼片段,與我們上面的查詢相同,並有年齡的附加條件。</font></font></p> + +<pre class="notranslate"><code>Athlete. + find(). + where('sport').equals('Tennis'). + where('age').gt(17).lt(50). //Additional where query + limit(5). + sort({ age: -1 }). + select('name age'). + exec(callback); // where callback is the name of our callback function.</code></pre> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#query_Query-find" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>find()</font></font></a><font><font><span> </span> 方法獲取所有匹配的記錄,但通常你只想獲得一個匹配。</font><font>以下方法可以查詢單個記錄:</font></font></p> + +<ul style='font-style: normal; margin: 0px 0px 24px; padding: 0px 0px 0px 40px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#model_Model.findById" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;">findById()</a></code><font><font>:用指定的</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>id<span> </span></code><font><font>查找文檔(每個文檔都有一個唯一的</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>id</code><font><font>)。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#query_Query-findOne" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;">findOne()</a></code><font><font>: 查找與指定條件匹配的單個文檔。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#model_Model.findByIdAndRemove" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;">findByIdAndRemove()</a></code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#model_Model.findByIdAndUpdate" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;">findByIdAndUpdate()</a></code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#query_Query-findOneAndRemove" rel="noopener" style="font-style: normal !important; text-decoration: underline; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;">findOneAndRemove()</a></code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;">findOneAndUpdate()</a></code><font><font>:通過</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>id<span> </span></code><font><font>或條件查找單個文檔,並更新或刪除它。</font><font>這些是用於更新和刪除記錄的有用便利功能。</font></font></li> +</ul> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>注意:</font></font></strong><font><font>還有一個</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#model_Model.count" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;">count()</a></code><font><font>方法,您可以使用它來獲取與條件匹配的項目數。</font><font>如果您想要在不實際提取記錄的情況下執行計數,這非常有用。</font></font></p> +</div> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>查詢可以做更多的事情。有關更多訊息,請參閱:</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/queries.html" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>查詢</font></font></a><font><font>(Mongoose文檔)。</font></font></p> + +<h4 id="運用相關文檔—_population方法" style='font-style: normal; line-height: 1.2; margin: 30px 0px 20px; padding: 0px; border: 0px; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 1.375rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>運用相關文檔— population方法</font></font></h4> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>您可以使用</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>ObjectId</code><font><font>綱要字段,從一個文檔/模型實例,創建一對一引用,或者使用</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>ObjectIds</code><font><font>數組,從一個文檔創建一對多的引用。</font><font>該字段存儲相關模型的ID。</font><font>如果需要關聯文檔的實際內容,可以在查詢中使用</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'><a class="external external-icon" href="http://mongoosejs.com/docs/api.html#query_Query-populate" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;">populate()</a></code><font><font>方法,將id替換為實際數據。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>例如,以下綱要定義作者和故事。</font><font>每個作者可以有多個故事,我們將其表示為一個</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>ObjectId</code><font><font>數組。</font><font>每個故事可以有一個作者。</font><font>綱要從“ref”(以粗體突出顯示)得知,可以分配給該字段的模型。</font></font></p> + +<pre class="brush: js notranslate"><code>var mongoose = require('mongoose') + , Schema = mongoose.Schema + +var authorSchema = Schema({ + name : String, + stories : [{ type: Schema.Types.ObjectId, <strong>ref</strong>: 'Story' }] +}); + +var storySchema = Schema({ + author : { type: Schema.Types.ObjectId, <strong>ref</strong>: 'Author' }, + title : String +}); + +var Story = mongoose.model('Story', storySchema); +var Author = mongoose.model('Author', authorSchema);</code></pre> + +<p><font><font>我們可以通過分配</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>_id</code><font><font>值,來保存對相關文檔的引用。</font><font>下面我們創建一個作者,然後創建一個故事,並將作者ID分配給我們的故事作者字段。</font></font></p> + +<pre class="brush: js notranslate"><code>var bob = new Author({ name: 'Bob Smith' }); + +bob.save(function (err) { + if (err) return handleError(err); + + //Bob now exists, so lets create a story + var story = new Story({ + title: "Bob goes sledding", + author: bob._id // assign the _id from the our author Bob. This ID is created by default! + }); + + story.save(function (err) { + if (err) return handleError(err); + // Bob now has his story + }); +});</code></pre> + +<p><font><font>我們的故事文檔,現在有作者文檔ID引用的作者。為了在我們的故事結果中,獲取作者訊息,我們使用</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>populate()</code><font><font>,如下所示。</font></font></p> + +<pre class="brush: js notranslate"><code>Story +.findOne({ title: 'Bob goes sledding' }) +.populate('author') //This populates the author id with actual author information! +.exec(function (err, story) { + if (err) return handleError(err); + console.log('The author is %s', story.author.name); + // prints "The author is Bob Smith" +});</code></pre> + +<div class="note"> +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 18px; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'><strong style="border: 0px; font-style: normal; font-weight: 700; margin: 0px; padding: 0px;"><font><font>注意:</font></font></strong><font><font>敏銳的讀者會注意到,我們在故事中添加了作者,但我們沒有做任何事情,來將我們的故事添加到作者的故事</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem;'>stories</code><font><font>數組中。</font><font>那麼我們怎樣才能得到特定作者的所有故事?</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 18px; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'><font><font>一種方法,是將作者添加到故事數組中,但這會導致我們需要在兩個地方,維護與作者和故事有關的訊息。更好的方法是獲取作者的</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem;'>_id</code><font><font>,然後使用</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem;'>find()</code><font><font>,在所有故事的作者字段中搜索此內容。</font></font></p> + +<pre class="brush: js notranslate"><code>Story +.find({ author : bob._id }) +.exec(function (err, stories) { + if (err) return handleError(err); + // returns all stories that have Bob's id as their author. +});</code> +</pre> +</div> + +<p><font><font>這幾乎是您在本教程中,使用相關項目時,需要了解的所有內容。有關更多詳細訊息,請參閱</font></font><a class="external external-icon" href="http://mongoosejs.com/docs/populate.html" rel="noopener" style='font-style: normal; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line; font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; background-color: rgb(255, 255, 255);'><font><font>Population</font></font></a><font><font>(Mongoose docs)。</font></font></p> + +<h3 id="一個檔案對應一個綱要模型"><span class="highlight-span" style="background-color: #333333; border: 0px; color: #ffffff; font-style: normal !important; font-weight: 400; line-height: 1.25; margin: 0px; padding: 0px 4px 0px 40px;"><font><font>一個檔案對應一個綱要/模型</font></font></span></h3> + +<p><font>雖然您可以使用任何喜歡的文件結構創建綱要和模型,但我們強烈建議在每個模型模塊(文件)中,定義每個模型綱要,導出方法以創建模型。</font><font>如下所示:</font></p> + +<pre class="brush: js notranslate"><code>// File: ./models/somemodel.js + +//Require Mongoose +var mongoose = require('mongoose'); + +//Define a schema +var Schema = mongoose.Schema; + +var SomeModelSchema = new Schema({ + a_string : String, + a_date : Date, +}); + +<strong>//Export function to create "SomeModel" model class +module.exports = mongoose.model('SomeModel', SomeModelSchema );</strong></code></pre> + +<p><font>然後,您可以在其他文件中,立即要求並使用該模型。</font><font>下面我們展示如何使用它,來獲取模型的所有實例。</font></p> + +<pre class="brush: js notranslate"><code>//Create a SomeModel model just by requiring the module +var SomeModel = require('../models/somemodel') + +// Use the SomeModel object (model) to find all SomeModel records +SomeModel.find(callback_function);</code></pre> + +<h2 id="架設MongoDB數據庫"><font><font>架設MongoDB數據庫</font></font></h2> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>現在我們了解了Mongoose能做什麼,以及我們想如何設計我們的模型,現在該開始在LocalLibrary網站上工作了。我們想要做的第一件事,就是設置一個MongoDb數據庫,我們可以使用它來儲存我們的圖書館數據。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>本教程,我們將使用</font></font><a class="external external-icon" href="https://mlab.com/welcome/" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>mLab</font></font></a><font><font>免費的雲託管的“<span> </span></font></font><a class="external external-icon" href="https://mlab.com/plans/pricing/" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>沙盒</font></font></a><font><font><span> </span>”數據庫。</font><font>這個數據庫層不適合生產環境的網站,因為它沒有冗餘設計,但它對於開發和原型設計來說非常有用。我們在這裡使用它,是因為它免費且易於設置,並且因為作為數據庫服務供應商來說,mLab是流行的數據庫選擇之一,您可能會合理選擇您的生產環境數據庫(撰寫本文時,其他流行的選擇包括</font></font><a class="external external-icon" href="https://www.compose.com/" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>Compose</font></font></a><font><font>、</font></font><a class="external external-icon" href="https://scalegrid.io/pricing.html" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>ScaleGrid</font></font></a><font><font>和</font></font><a class="external external-icon" href="https://www.mongodb.com/cloud/atlas" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>MongoDB Atlas</font></font></a><font><font>)。</font></font></p> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>注意:</font></font></strong><font><font>如果您願意,可以下載並安裝</font></font><a class="external external-icon" href="https://www.mongodb.com/download-center" rel="noopener" style='font-style: normal; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 18px; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; background-color: rgb(255, 243, 212);'><font><font>與系統相對應的二進製文件</font></font></a><font><font>,在本地設置MongoDb數據庫。</font><font>除了您在連接時指定的數據庫URL之外,本文中的其餘指令將很類似。</font></font></p> +</div> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>您首先需要</font></font><a class="external external-icon" href="https://mlab.com/signup/" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>使用mLab創建一個賬戶</font></font></a><font><font>(這是免費的,只需要輸入基本聯繫訊息,並確認其服務條款)。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>登錄後,您將進入</font></font><font><font><a class="external external-icon" href="https://mlab.com/home" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;">mLab主</a>畫面</font></font><font><font>:</font></font></p> + +<ol> + <li><font><font>單擊</font></font><em><font><font>MongoDB Deployments</font></font></em><font><font>部分中的</font></font><strong style='background-color: #ffffff; border: 0px; color: #333333; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; letter-spacing: normal; margin: 0px; padding: 0px; text-align: left; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>Create New。</font></font></strong><img alt="" src="https://mdn.mozillademos.org/files/14446/mLabCreateNewDeployment.png" style="height: 415px; width: 1000px;"></li> + <li><span style='background-color: #ffffff; color: #333333; display: inline !important; float: none; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; font-weight: 400; letter-spacing: normal; text-align: left; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'>這將打開“雲提供商”Cloud Provider 選擇畫面。</span><br> + <img alt="MLab - screen for new deployment" src="https://mdn.mozillademos.org/files/15661/mLab_new_deployment_form_v2.png" style="height: 931px; width: 1297px;"><br> + + <ul> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>從“計劃類型”Plan Type 部分中,選擇“SANDBOX(免費)”計劃。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>從“雲提供商”<span> </span></font></font><em><font><font>Cloud Provider</font></font></em><font><font>部分,選擇任意提供商。</font><font>不同的提供商,提供不同的地區(顯示在選定的計劃類型下面)。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>單擊“繼續”<span> </span></font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>Continue</font></font></strong><font><font>按鈕。</font></font></li> + </ul> + </li> + <li><font><font>這將打開“選擇區域”<span> </span></font></font><em><font><font>Select Region </font></font></em><font><font>畫面。</font></font> + <p><img alt="Select new region screen" src="https://mdn.mozillademos.org/files/15662/mLab_new_deployment_select_region_v2.png" style="height: 570px; width: 1293px;"></p> + + <ul> + <li> + <p><font><font>選擇離您最近的地區,然後選擇繼續</font></font><strong style='background-color: #ffffff; border: 0px; color: #333333; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; letter-spacing: normal; margin: 0px; padding: 0px; text-align: left; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>Continue</font></font></strong><font><font><span> </span>.</font></font></p> + </li> + </ul> + </li> + <li> + <p><span style='background-color: #ffffff; color: #333333; display: inline !important; float: none; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; font-weight: 400; letter-spacing: normal; text-align: left; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'>這將打開 Final Details </span><font><font>畫面</font></font><span style='background-color: #ffffff; color: #333333; display: inline !important; float: none; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; font-weight: 400; letter-spacing: normal; text-align: left; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'>。</span><br> + <img alt="New deployment database name" src="https://mdn.mozillademos.org/files/15663/mLab_new_deployment_final_details.png" style="height: 569px; width: 1293px;"></p> + + <ul> + <li> + <p><font><font>輸入新數據庫的名稱</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>local_library</code><font><font>,然後選擇繼續</font></font><strong style='background-color: #ffffff; border: 0px; color: #333333; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; letter-spacing: normal; margin: 0px; padding: 0px; text-align: left; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>Continue</font></font></strong><font><font>。</font></font></p> + </li> + </ul> + </li> + <li> + <p><span style='background-color: #ffffff; color: #333333; display: inline !important; float: none; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; font-weight: 400; letter-spacing: normal; text-align: left; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'>這將打開訂單確認畫面。</span><br> + <img alt="Order confirmation screen" src="https://mdn.mozillademos.org/files/15664/mLab_new_deployment_order_confirmation.png" style="height: 687px; width: 1290px;"></p> + + <ul> + <li> + <p><font><font>單擊“提交訂單”<span> </span></font></font><strong style='background-color: #ffffff; border: 0px; color: #333333; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; letter-spacing: normal; margin: 0px; padding: 0px; text-align: left; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>Submit Order</font></font></strong><font><font>以創建數據庫。</font></font></p> + </li> + </ul> + </li> + <li> + <p><font>您將返回到主</font><span style='background-color: #ffffff; color: #333333; display: inline !important; float: none; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; font-weight: 400; letter-spacing: normal; text-align: left; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'>畫面</span><font>。單擊剛剛創建的新數據庫,以打開其詳細<font>訊息</font></font><span style='background-color: #ffffff; color: #333333; display: inline !important; float: none; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; font-weight: 400; letter-spacing: normal; text-align: left; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'>畫面</span><font>。正如你所看到的,數據庫沒有集合(數據)。</font><br> + <img alt="mLab - Database details screen" src="https://mdn.mozillademos.org/files/15665/mLab_new_deployment_database_details.png" style="height: 700px; width: 1398px;"><br> + <font>您需要用來訪問數據庫的URL,顯示在上面的表單中(如上圖所示)。</font><font>為了使用它,您需要創建一個可以在URL中指定的數據庫用戶。</font></p> + </li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>單擊用戶</font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>Users</font></font></strong><font><font>選項卡,並選擇添加數據庫用戶按鈕</font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>Add database user</font></font></strong><font><font>。</font></font></li> + <li><font><font>輸入用戶名和密碼(兩次),然後按創建</font></font><strong style='background-color: #ffffff; border: 0px; color: #333333; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; letter-spacing: normal; margin: 0px; padding: 0px; text-align: left; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>Create</font></font></strong><font><font>。</font><font>不要選擇只讀</font></font><em><font><font>read-only</font></font></em><font><font>。</font></font><br> + <img alt="" src="https://mdn.mozillademos.org/files/14454/mLab_database_users.png" style="height: 204px; width: 600px;"></li> +</ol> + +<p><font><font>您現在已經創建了數據庫,並且有一個可以用來訪問它的URL(帶有用戶名和密碼)。</font><font>這看起來像是這樣的:</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>mongodb://your_user_namer:your_password@ds119748.mlab.com:19748/local_library</code><font><font>.</font></font></p> + +<h2 id="安裝_Mongoose" style='font-style: normal; line-height: 1.2; margin: 103px 0px 20px; padding: 0px; border: 0px; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 2.5rem; position: relative; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>安裝 Mongoose</font></font></h2> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>打開命令提示符,並到您創建</font></font><a href="https://developer.mozilla.org/zh-CN/docs/Learn/Server-side/Express_Nodejs/skeleton_website" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px;"><font><font>本地圖書館骨架網站</font></font></a><font><font>的目錄。</font><font>輸入以下命令,安裝Mongoose(及其依賴項),並將其添加到您的</font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>package.json</font></font></strong><font><font>文件中,除非您在閱讀上述</font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>Mongoose入門</font></font></strong><font><font>時,已經這樣做了。</font></font></p> + +<pre class="brush: bash notranslate">npm install mongoose +</pre> + +<h2 id="連接到_MongoDB" style='font-style: normal; line-height: 1.2; margin: 103px 0px 20px; padding: 0px; border: 0px; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 2.5rem; position: relative; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>連接到 MongoDB</font></font></h2> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>打開</font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>/app.js</font></font></strong><font><font>(位於項目的根目錄),並在宣告Express應用程序對象的位置(在</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>var app = express();</code><font><font>之後)複製以下文本。</font><font>將數據庫url字符串('insert_your_database_url_here')替換為表示您自己的數據庫的位置URL(即是使用</font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>來自上面mLab</font></font></strong><font><font>的訊息)。</font></font></p> + +<pre class="brush: js notranslate">//Set up mongoose connection +var mongoose = require('mongoose'); +var mongoDB = '<em>insert_your_database_url_here</em>'; +mongoose.connect(mongoDB); +mongoose.Promise = global.Promise; +var db = mongoose.connection; +db.on('error', console.error.bind(console, 'MongoDB connection error:'));</pre> + +<p><font><font>正如上面的</font></font><strong style='background-color: #ffffff; border: 0px; color: #333333; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>Mongoose入門</font></font></strong><font><font>中所討論的,此代碼創建了與數據庫的默認連接,並綁定到錯誤事件(以便將錯誤打印到控制台)。</font></font></p> + +<h2 id="定義本地圖書館綱要" style='font-style: normal; line-height: 1.2; margin: 103px 0px 20px; padding: 0px; border: 0px; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 2.5rem; position: relative; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>定義本地圖書館綱要</font></font></h2> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>如上所述,我們將為每個模型定義一個單獨的模塊。</font><font>首先在項目根目錄(</font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>/models</font></font></strong><font><font>)中,為我們的模型創建一個文件夾,然後為每個模型創建單獨的文件:</font></font></p> + +<pre class="notranslate">/express-locallibrary-tutorial //the project root + <strong>/models</strong> + <strong>author.js</strong> + <strong>book.js</strong> + <strong>bookinstance.js</strong> + <strong>genre.js</strong> +</pre> + +<h3 id="作者模型"><span class="highlight-span" style="background-color: #333333; border: 0px; color: #ffffff; font-style: normal !important; font-weight: 400; line-height: 1.25; margin: 0px; padding: 0px 4px 0px 40px;"><font><font>作者模型</font></font></span></h3> + +<p><font><font>複製下面顯示的</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>Author</code><font><font>作者綱要代碼,並將其粘貼到</font></font><strong style='background-color: #ffffff; border: 0px; color: #333333; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>./models/author.js</font></font></strong><font><font>文件中。</font><font>該綱要定義了一個作者,具有</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>String</code><font><font>SchemaTypes的第一個名稱和家族名稱,這是必需的,最多有100個字符,</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>Date</code><font><font>字段為出生和死亡日期。</font></font></p> + +<pre class="brush: js notranslate">var mongoose = require('mongoose'); + +var Schema = mongoose.Schema; + +var AuthorSchema = new Schema( + { + first_name: {type: String, required: true, max: 100}, + family_name: {type: String, required: true, max: 100}, + date_of_birth: {type: Date}, + date_of_death: {type: Date}, + } +); + +<strong>// Virtual for author's full name +AuthorSchema +.virtual('name') +.get(function () { + return this.family_name + ', ' + this.first_name; +});</strong> + +// Virtual for author's URL +AuthorSchema +.virtual('url') +.get(function () { + return '/catalog/author/' + this._id; +}); + +//Export model +module.exports = mongoose.model('Author', AuthorSchema); + +</pre> + +<p><span style='background-color: #ffffff; color: #333333; display: inline !important; float: none; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; font-weight: 400; letter-spacing: normal; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'>我們還為AuthorSchema,聲明了一個名為“url”的虛擬屬性,它返回獲取模型的特定實例所需的絕對URL — 每當我們需要獲取指向特定作者的鏈接時,我們將在模板中使用該屬性。</span></p> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>注意:</font></font></strong><font><font>在綱要中聲明我們的URL是虛擬的,這是一個好主意,因為一個項目的URL只需要在一個地方更改。</font><font>此時,使用此URL的鏈接將不起作用,因為我們還沒有任何路由,可以處理個別模型實例的代碼。</font><font>我們將在後面的文章中介紹這些內容!</font></font></p> +</div> + +<p><span style='background-color: #ffffff; color: #333333; display: inline !important; float: none; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; font-weight: 400; letter-spacing: normal; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'>在模塊的最後,我們導出了模型。</span></p> + +<h3 class="highlight-spanned" id="書本模型" style='font-style: normal; line-height: 1.25; margin: 20px 0px; padding: 0px; border: 0px; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 1.5rem; background-color: rgb(255, 255, 255); color: rgb(51, 51, 51); font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'><span class="highlight-span" style="background-color: #333333; border: 0px; color: #ffffff; font-style: normal !important; font-weight: 400; line-height: 1.25; margin: 0px; padding: 0px 4px 0px 40px;"><font><font>書本模型</font></font></span></h3> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>複製下面顯示的</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>Book</code><font><font>綱要代碼,並將其粘貼到</font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>./models/book.js</font></font></strong><font><font>文件中。</font><font>其中大部分與作者模型相似—我們已經聲明了一個具有多個字符串字段的綱要,以及一個虛擬屬性,用於獲取特定書籍記錄的URL,並且我們已經導出了模型。</font></font></p> + +<pre class="brush: js notranslate">var mongoose = require('mongoose'); + +var Schema = mongoose.Schema; + +var BookSchema = new Schema( + { + title: {type: String, required: true}, + <strong> author: {type: Schema.Types.ObjectId, ref: 'Author', required: true},</strong> + summary: {type: String, required: true}, + isbn: {type: String, required: true}, + <strong> genre: [{type: Schema.Types.ObjectId, ref: 'Genre'}]</strong> + } +); + +// Virtual for book's URL +BookSchema +.virtual('url') +.get(function () { + return '/catalog/book/' + this._id; +}); + +//Export model +module.exports = mongoose.model('Book', BookSchema); +</pre> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>這裡的主要區別,是我們已經創建了兩個對其他模型的引用:</font></font></p> + +<ul style='font-style: normal; margin: 0px 0px 24px; padding: 0px 0px 0px 40px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>作者是對單個</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>Author</code><font><font>作者模型對象的引用,並且是必要的。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>種類是對</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>Genre</code><font><font>種類模型對像數組的引用。</font><font>我們還沒有宣告這個對象!</font></font></li> +</ul> + +<h3 id="書本實例模型"><span class="highlight-span" style="background-color: #333333; border: 0px; color: #ffffff; font-style: normal !important; font-weight: 400; line-height: 1.25; margin: 0px; padding: 0px 4px 0px 40px;"><font><font>書本實例模型</font></font></span></h3> + +<p><font><font>最後,複製下面顯示的</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>BookInstance</code><font><font>綱要代碼,並將其粘貼到</font></font><strong style='background-color: #ffffff; border: 0px; color: #333333; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>./models/bookinstance.js</font></font></strong><font><font>文件中。</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>BookInstance</code><font><font>表示某人可能藉閱的書籍的特定副本,並包含有關該副本是否可用,或預期返回日期的訊息,“印記”或版本詳細訊息。</font></font></p> + +<pre class="brush: js notranslate">var mongoose = require('mongoose'); + +var Schema = mongoose.Schema; + +var BookInstanceSchema = new Schema( + { + book: { type: Schema.Types.ObjectId, ref: 'Book', required: true }, //reference to the associated book + imprint: {type: String, required: true}, + status: {type: String, required: true, <strong>enum: ['Available', 'Maintenance', 'Loaned', 'Reserved']</strong>, <strong>default: 'Maintenance'</strong>}, + due_back: {type: Date, <strong>default: Date.now</strong>} + } +); + +// Virtual for bookinstance's URL +BookInstanceSchema +.virtual('url') +.get(function () { + return '/catalog/bookinstance/' + this._id; +}); + +//Export model +module.exports = mongoose.model('BookInstance', BookInstanceSchema);</pre> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>我們在這裡展示的新東西,是字段選項:</font></font></p> + +<ul style='font-style: normal; margin: 0px 0px 24px; padding: 0px 0px 0px 40px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>枚舉</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>enum</code><font><font>:這允許我們設置字符串的允許值。</font><font>在這種情況下,我們用它來指定我們書籍的可用性狀態(使用枚舉,意味著我們可以防止錯誤拼寫和任意值,成為我們的狀態)</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>默認值</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>default</code><font><font>:我們使用默認值,將新創 建的書本實例的默認狀態,設置為維護,並將默認的</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>due_back</code><font><font>日期,設置為現在</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>now</code><font><font>(請注意在設置日期時,如何調用Date函數!)</font></font></li> +</ul> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>其他所有內容,大夥應該在前面教程裡邊已經熟悉了。</font></font></p> + +<h3 id="種類模型-自我挑戰!"><span class="highlight-span" style="background-color: #333333; border: 0px; color: #ffffff; font-style: normal !important; font-weight: 400; line-height: 1.25; margin: 0px; padding: 0px 4px 0px 40px;"><font><font>種類模型-自我挑戰!</font></font></span></h3> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>打開你的</font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>./models/genre.js</font></font></strong><font><font>文件,並創建一個存儲類型的綱要(書本的類別,例如它是小說還是非小說,浪漫史或軍事歷史等)。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>該定義將與其他模型非常相似:</font></font></p> + +<ul style='font-style: normal; margin: 0px 0px 24px; padding: 0px 0px 0px 40px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>該模型應該有一個名為</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>name</code><font><font>的</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>String</code><font><font>SchemaType ,來描述種類。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>這個</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>name</code><font><font>字段應該是必要的,並且有3到100個字符。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>為類型的URL聲明虛擬,名為</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>url</code><font><font>。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>導出模型。</font></font></li> +</ul> + +<h2 id="測試—創建一些項目"><font><font>測試—創建一些項目</font></font></h2> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>就是這樣。</font><font>我們現在已經為該網站建立了所有模型!</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>為了測試這些模型(並創建一些示例書籍,和其他項目以便於我們在後面文章使用),現在我們將運行一個獨立的腳本來創建每種類型的項目:</font></font></p> + +<ol> + <li><font><font>在express-locallibrary-tutorial目錄下(與</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>package.json</code><font><font>處於同一級別),下載(或以其他方式創建)文件</font></font><a class="external external-icon" href="https://raw.githubusercontent.com/hamishwillee/express-locallibrary-tutorial/master/populatedb.js" rel="noopener" style='font-style: normal; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line; font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: left; text-indent: 0px; text-transform: none; background-color: rgb(255, 255, 255);'><font><font>populatedb.js</font></font></a><font><font>。</font></font> + + <div class="note"> + <p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: left; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>注意:</font></font></strong><font><font>您不需要知道</font></font><a class="external external-icon" href="https://raw.githubusercontent.com/hamishwillee/express-locallibrary-tutorial/master/populatedb.js" rel="noopener" style='font-style: normal; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 18px; font-weight: 400; letter-spacing: normal; text-align: left; text-indent: 0px; text-transform: none; background-color: rgb(255, 243, 212);'><font><font>populatedb.js</font></font></a><font><font>的工作原理;它只是將示例數據添加到數據庫中。</font></font></p> + </div> + </li> + <li><span style='background-color: #ffffff; color: #333333; display: inline !important; float: none; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; font-weight: 400; letter-spacing: normal; text-align: left; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'>在項目根目錄中,輸入以下命令,以安裝腳本所需的異步模塊(我們將在後面的教程中討論這一點)</span> + <pre class="brush: bash notranslate">npm install async</pre> + </li> + <li><font><font>在命令提示符下,使用node運行此腳本,傳遞MongoDB數據庫的URL(與之前在</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>app.js</code><font><font>中替換insert_your_database_url_here佔位符的那個相同):</font></font> + <pre class="brush: bash notranslate">node populatedb <your mongodb url></pre> + </li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>該腳本應一路運行至完成,並在終端中創建它們時顯示各項目。</font></font></li> +</ol> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>提示:</font></font></strong><font><font>至</font></font><a class="external external-icon" href="https://mlab.com/home" rel="noopener" style='font-style: normal; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 18px; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; background-color: rgb(255, 243, 212);'><font><font>mLab</font></font></a><font><font>上的數據庫。</font><font>您現在應該可以深入到書本籍,作者,種類和書本實例的各個集合中,並查看單個文檔。</font></font></p> +</div> + +<h2 id="總結"><font><font>總結</font></font></h2> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>本文中我們學到了一點數據庫和Node/Express的ORMs,更多的是關於如何定義Mongoose綱要與模型。</font><font>然後我們使用這些知識,為本地圖書館網站設計並實作出書本</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>Book</code><font><font>,書本實例</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>BookInstance</code><font><font>,作者</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>Author</code><font><font>和種類</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>Genre</code><font><font>模型。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>最後,我們創建一些實例,以測試模型(使用獨立運作的命令稿)。</font><font>下一篇文章,我們將關注於如何創建一些網頁,以呈現這些物件。</font></font></p> + +<h2 id="參閱">參閱</h2> + +<ul> + <li><a href="https://expressjs.com/en/guide/database-integration.html">Database integration</a> (Express docs)</li> + <li><a href="http://mongoosejs.com/">Mongoose website</a> (Mongoose docs)</li> + <li><a href="http://mongoosejs.com/docs/guide.html">Mongoose Guide</a> (Mongoose docs)</li> + <li><a href="http://mongoosejs.com/docs/validation.html">Validation</a> (Mongoose docs)</li> + <li><a href="http://mongoosejs.com/docs/schematypes.html">Schema Types</a> (Mongoose docs)</li> + <li><a href="http://mongoosejs.com/docs/models.html">Models</a> (Mongoose docs)</li> + <li><a href="http://mongoosejs.com/docs/queries.html">Queries</a> (Mongoose docs)</li> + <li><a href="http://mongoosejs.com/docs/populate.html">Population</a> (Mongoose docs)</li> +</ul> + +<p>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/skeleton_website", "Learn/Server-side/Express_Nodejs/routes", "Learn/Server-side/Express_Nodejs")}}</p> + +<h2 id="本教程連結"><font><font>本教程連結</font></font></h2> + +<ul> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node introduction</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">Setting up a Node (Express) development environment</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Express Tutorial: The Local Library website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Express Tutorial Part 2: Creating a skeleton website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Express Tutorial Part 3: Using a Database (with Mongoose)</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/routes">Express Tutorial Part 4: Routes and controllers</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/deployment">Express Tutorial Part 7: Deploying to production</a></li> +</ul> diff --git a/files/zh-tw/learn/server-side/express_nodejs/routes/index.html b/files/zh-tw/learn/server-side/express_nodejs/routes/index.html new file mode 100644 index 0000000000..f4549ec598 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/routes/index.html @@ -0,0 +1,646 @@ +--- +title: 'Express 教學 4: 路由與控制器' +slug: Learn/Server-side/Express_Nodejs/routes +translation_of: Learn/Server-side/Express_Nodejs/routes +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs/Displaying_data", "Learn/Server-side/Express_Nodejs")}}</div> + +<p class="summary">在本教程中,我們將為最終在 本地圖書館 網站中需要的所有資源端點,搭配 "空殼" 處理函式來配置路由 (URL handling code) 。完成後,我們的路由處理源碼將會有模組化結構,在接下來的文章中,我們可以用真實的處理函式加以擴充。我們也會對如何使用Express 創建模組化路由,有更好的理解。</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">先備知識:</th> + <td>閱讀 <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node 介紹</a>。 完成先前教學主題 (包含 <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Express 教學 3: 使用資料庫 (Mongoose)</a>).</td> + </tr> + <tr> + <th scope="row">目標:</th> + <td><font>理解如何創建簡易路由配置。</font><font>我們所有的URL端點。</font></td> + </tr> + </tbody> +</table> + +<h2 id="概覽">概覽</h2> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>在</font></font><a href="https://developer.mozilla.org/zh-CN/docs/Learn/Server-side/Express_Nodejs/mongoose" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px;"><font><font>上一篇教程文章</font></font></a><font><font>中,我們定義了Mongoose模型,以與數據庫互動,並使用(獨立)腳本創建一些初始庫記錄。</font><font>現在我們可以編寫代碼,向用戶展示這些信息。</font><font>我們需要做的第一件事,是確定我們希望能夠在頁面中顯示哪些信息,然後定義適當的URL,以返回這些資源。</font><font>然後我們將需要創建路由(URL處理程序)和視圖(模板)來顯示這些頁面。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>下圖是作為處理HTTP請求/響應時,需要實現的主要數據流和事項的提醒。</font><font>除了視圖和路線之外,圖表還顯示“控制器” — 實際處理請求的函數,那些與路由請求分開的代碼。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>由於我們已經創建了模型,我們需要創建的主要內容是:</font></font></p> + +<ul style='font-style: normal; margin: 0px 0px 24px; padding: 0px 0px 0px 40px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>“路由”將支持的請求(以及請求URL中編碼的任何信息)轉發到適當的控制器功能。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>控制器用於從模型中獲取請求的數據,創建一個顯示數據的HTML頁面,並將其返回給用戶,以在瀏覽器中查看。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>視圖(模板)則由控制器用來呈現數據。</font></font></li> +</ul> + +<p> </p> + +<p><img alt="" src="https://mdn.mozillademos.org/files/14456/MVC%20Express.png" style="height: 460px; width: 800px;"></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>最終,我們可能會有頁面顯示書籍,流派,作者和書籍的列表和詳細信息,以及用於創建,更新和刪除記錄的頁面。</font><font>對一篇文章來說,這是很多的內容。</font><font>因此,本文的大部分內容,都將集中在設置我們的路由和控制器,以返回“虛擬”內容。</font><font>我們將在後續文章中,擴展控制器方法,以使用模型數據。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>下面的第一部分,提供了關於如何使用</font></font><a class="external external-icon" href="http://expressjs.com/en/4x/api.html#router" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;"><font><font>Express Router</font></font></a><font><font>中間件的簡要“入門”。</font><font>當我們設置LocalLibrary路由時,我們將在後面的章節中使用這些知識。</font></font></p> + +<h2 id="路由入門" style='font-style: normal; line-height: 1.2; margin: 103px 0px 20px; padding: 0px; border: 0px; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 2.5rem; position: relative; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>路由入門</font></font></h2> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>路由是Express代碼的一部分,它將HTTP動詞(</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>GET</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>POST</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>PUT</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>DELETE</code><font><font>等),URL路徑/模式和被調用來處理該模式的函數,相關聯起來。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>有幾種方法可以創建路線。</font><font>本教程將使用</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'><a class="external external-icon" href="http://expressjs.com/en/guide/routing.html#express-router" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;">express.Router</a></code><font><font>中間件,因為它允許我們將站點的特定部分的路由處理程序組合在一起,並使用通用的路由前綴訪問它們。</font><font>我們會將所有與圖書館有關的路由,保存在“目錄”模塊中,如果我們添加路由來處理用戶帳戶或其他功能,我們可以將它們分開保存。</font></font></p> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>注意:</font></font></strong><font><font>我們在</font></font><a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction#Creating_route_handlers" style='font-style: normal; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 18px; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 243, 212);'><font><font>Express簡介>創建路由處理程序</font></font></a><font><font>中,簡要討論了Express應用程序路由。</font><font>除了為模塊化提供更好的支持之外(如下面第一小節所述),使用Router非常類似於直接在Express應用程序對像上定義路由。</font></font></p> +</div> + +<p><font><font>本節的其餘部分,概述瞭如何使用路由器</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>Router</code><font><font>來定義路由。</font></font></p> + +<h3 id="定義和使用單獨的路由模塊"><span class="highlight-span" style="background-color: #333333; border: 0px; color: #ffffff; font-style: normal !important; font-weight: 400; line-height: 1.25; margin: 0px; padding: 0px 4px 0px 40px;"><font><font>定義和使用單獨的路由模塊</font></font></span></h3> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>下面的代碼提供了一個具體示例,說明我們如何創建路由模塊,然後在Express應用程序中使用它。</font><font>首先,我們在一個名為</font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>wiki.js</font></font></strong><font><font>的模塊中創建一個wiki的路由。</font><font>代碼首先導入Express應用程序對象,使用它獲取一個</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>Router</code><font><font>對象,然後使用</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>get()</code><font><font>方法向其添加一對路由。</font><font>所有模塊的最後一個導出路由器</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>Router</code><font><font>對象。</font></font></p> + +<pre class="brush: js"><code>// wiki.js - Wiki route module. + +var express = require('express'); +var router = express.Router(); + +// Home page route. +router.get('/', function (req, res) { + res.send('Wiki home page'); +}) + +// About page route. +router.get('/about', function (req, res) { + res.send('About this wiki'); +}) + +module.exports = router;</code> + +</pre> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>注意:</font></font></strong><font><font>上面我們直接在路由器函數中定義路由處理程序回調。</font><font>在LocalLibrary中,我們將在一個單獨的控制器模塊中,定義這些回調。</font></font></p> +</div> + +<p><font><font>要在主應用程序文件中使用路由器模塊,我們首先</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>require()</code><font><font>路由模塊(</font></font><strong style='background-color: #ffffff; border: 0px; color: #333333; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>wiki.js</font></font></strong><font><font>)。</font><font>然後,我們在Express應用程序上調用</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>use()</code><font><font>,將路由器添加到中間件處理路徑,並指定一個'wiki'的URL路徑。</font></font></p> + +<pre class="brush: js"><code>var wiki = require('./wiki.js'); +// ... +app.use('/wiki', wiki);</code></pre> + +<p><font><font>然後可以從</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>/wiki/</code><font><font>和</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>/wiki/about/</code><font><font>,訪問我們的wiki路由模塊中定義的兩個路由。</font></font></p> + +<h3 id="路由函數"><span class="highlight-span" style="background-color: #333333; border: 0px; color: #ffffff; font-style: normal !important; font-weight: 400; line-height: 1.25; margin: 0px; padding: 0px 4px 0px 40px;"><font><font>路由函數</font></font></span></h3> + +<p><font><font>我們上面的模塊,定義了幾個典型的路由功能。</font><font>使用</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>Router.get()</code><font><font>方法定義“about”路由(在下面),該方法僅響應HTTP GET請求。</font><font>此方法的第一個參數是URL路徑,而第二個參數是一個回調函數,如果收到帶有路徑的HTTP GET請求,將會調用該函數。</font></font></p> + +<pre class="brush: js"><code>router.get('/about', function (req, res) { + res.send('About this wiki'); +})</code> +</pre> + +<p><font><font>回調函數接受三個參數(通常如下所示命名:</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>req</code><font><font>,<span> </span></font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>res</code><font><font>,<span> </span></font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>next</code><font><font>),它將包含HTTP請求對象,HTTP響應,以及中間件鏈中的下一個函數。</font></font></p> + +<div class="note"> +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 18px; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'><strong style="border: 0px; font-style: normal; font-weight: 700; margin: 0px; padding: 0px;"><font><font>注意:</font></font></strong><font><font>路由器功能是</font></font><a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction#Using_middleware" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px;"><font><font>Express中間件</font></font></a><font><font>,這意味著它們必須完成(響應)請求或調用鏈中的下一個功能</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem;'>next</code><font><font>。</font><font>在上面的例子中,我們使用</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem;'>send()</code><font><font>完成了請求,所以下一個參數</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem;'>next</code><font><font>沒有被使用(我們選擇不指定它)。</font></font></p> + +<p style='font-style: normal; margin: 0px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 18px; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'><font><font>上面的路由器函數只需要一次回調,但您可以根據需要指定任意數量的回調參數,或一組回調函數。</font><font>每個函數都是中間件鏈的一部分,並且將按照添加到鏈中的順序調用(除非前面的函數完成請求)。</font></font></p> + +<p> </p> +</div> + +<p><font><font>這裡的回調函數,在響應中調用</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'><a class="external external-icon" href="https://expressjs.com/en/4x/api.html#res.send" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;">send()</a></code><font><font>,當我們收到帶有路徑('<span> </span></font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>/about'</code><font><font>)的GET請求時,返回字符串“About this wiki”。</font><font>有</font></font><a class="external external-icon" href="https://expressjs.com/en/guide/routing.html#response-methods" rel="noopener" style='font-style: normal; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line; font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; background-color: rgb(255, 255, 255);'><font><font>許多其他響應方法</font></font></a><font><font>,可以結束請求/響應週期。</font><font>例如,您可以調用</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'><a class="external external-icon" href="https://expressjs.com/en/4x/api.html#res.json" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;">res.json()</a></code><font><font>,來發送JSON響應,或調用</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; color: rgb(51, 51, 51); font-size: medium; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'><a class="external external-icon" href="https://expressjs.com/en/4x/api.html#res.sendFile" rel="noopener" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line;">res.sendFile()</a></code><font><font>來發送文件。</font><font>構建庫時,我們最常使用的響應方法是</font></font><a class="external external-icon" href="https://expressjs.com/en/4x/api.html#res.render" rel="noopener" style='font-style: normal; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line; font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; background-color: rgb(255, 255, 255);'><font><font>render()</font></font></a><font><font>,它使用模板和數據創建並返回HTML文件—我們將在後面的文章中,進一步討論這個問題!</font></font></p> + +<h3 id="HTTP_動詞"><span class="highlight-span" style="background-color: #333333; border: 0px; color: #ffffff; font-style: normal !important; font-weight: 400; line-height: 1.25; margin: 0px; padding: 0px 4px 0px 40px;"><font><font><span> </span>HTTP 動詞</font></font></span></h3> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>上面的示例路由使用</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>Router.get()</code><font><font>方法,響應具有特定路徑的HTTP GET請求。</font><font>路由器</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>Router</code><font><font>還為所有其他HTTP動詞提供路由方法,這些方法多數以完全相同的方式使用:</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>post()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>put()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>delete()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>options()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>trace()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>copy()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>lock()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>mkcol()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>move()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>purge()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>propfind()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>proppatch()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>unlock()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>report()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>mkactivity()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>checkout()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>merge()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>m-</code><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>search()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>notify()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>subscribe()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>unsubscribe()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>patch()</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>search()</code><font><font>,和</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>connect()</code><font><font>。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>例如,下面的代碼就像上一個</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>/about</code><font><font>路由一樣,但只響應HTTP POST請求。</font></font></p> + +<pre class="brush: js"><code>router.post('/about', function (req, res) { + res.send('About this wiki'); +})</code></pre> + +<h3 id="路由路徑"><span class="highlight-span" style="background-color: #333333; border: 0px; color: #ffffff; font-style: normal !important; font-weight: 400; line-height: 1.25; margin: 0px; padding: 0px 4px 0px 40px;"><font><font>路由路徑</font></font></span></h3> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>路由路徑定義可以進行請求的端點。</font><font>我們到目前為止看到的例子,都是字符串,並且完全按照字符串的寫法使用:'/','/ about','/ book','/any-random.path'。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>路由路徑也可以是字符串模式。</font><font>字符串模式使用正則表達式語法的子集,來定義將匹配的端點模式。</font><font>下面列出了子集(請注意,連字符(</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>-</code><font><font>)和點(</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>.</code><font><font>)由字符串路徑字面解釋):</font></font></p> + +<ul style='font-style: normal; margin: 0px 0px 24px; padding: 0px 0px 0px 40px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>? :端點在?號前面的那個字符,必須為0個或1個。</font><font>例如。</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>'/ab?cd'</code><font><font>的路徑路徑將匹配端點</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>acd<span> </span></code><font><font>或</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>abcd</code><font><font>。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>+ :端點在+號前面的那個字符,必須為1個或多個。</font><font>例如,</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>'/ab+cd'</code><font><font>的路徑路徑將與端點</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>abcd</code><font><font>,</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>abbcd</code><font><font>,</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>abbbcd</code><font><font>等匹配。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>* :端點在放置*字符的地方,可以代換為任意字符串。</font><font>例如。</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>'ab\*cd'</code><font><font>的路由路徑,將匹配端點</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>abcd</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>abXcd</code><font><font>,<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>abSOMErandomTEXTcd</code><font><font>等。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><font><font>() :將一組字符進行匹配,以執行上面三個操作。</font><font>例如。</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>'/ab(cd)?e'</code><font><font>,表示以?</font><font>號對(cd)進行匹配-它會匹配</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>abe</code><font><font>和</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>abcde</code><font><font>。</font><font>(譯註:即(cd)必須為0個或1個。若為0,匹配</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>abe</code><font><font>。若為1,匹配</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>abcde</code><font><font>)</font></font></li> +</ul> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>路由路徑也可以是</font></font><a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Regular_Expressions" style="font-style: normal !important; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px;"><font><font>JavaScript正則表達式</font></font></a><font><font>。</font><font>例如,下面的路由路徑將與鯰魚</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>catfish<span> </span></code><font><font>和角鯊魚</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>dogfish</code><font><font>相匹配,但不包括鯰魚</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>catflap</code><font><font>、鯰魚頭</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>catfishhead</code><font><font>等。</font><font>請注意,正則表達式的路徑使用正則表達式語法(它不像以前那樣,是帶引號的字符串)。</font></font></p> + +<pre class="brush: js"><code>app.get(/.*fish$/, function (req, res) { + ... +})</code></pre> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>注意:</font></font></strong><font><font><span> </span>LocalLibrary的大部分路由,都只使用字符串,而不是字符串模式和正則表達式。</font><font>我們還將使用下一節中討論的路由參數。</font></font></p> +</div> + +<h3 id="路由參數"><span class="highlight-span" style="background-color: #333333; border: 0px; color: #ffffff; font-style: normal !important; font-weight: 400; line-height: 1.25; margin: 0px; padding: 0px 4px 0px 40px;"><font><font>路由參數</font></font></span></h3> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>路徑參數是命名的URL段,用於捕獲在URL中的位置指定的值。</font><font>命名段以冒號為前綴,然後是名稱(例如</font><font>。捕獲的值,使用參數名稱作為鍵,存在</font><font>對像中(例如</font><font>)。</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>/<strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;">:</strong>your_parameter_name/</code><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>req.params</code><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>req.params.your_parameter_name</code></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>例如,考慮一個編碼的URL,其中包含有關用戶和書本的信息:</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>http://localhost:3000/users/34/books/8989</code><font><font>。</font><font>我們可以使用</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>userId</code><font><font>和</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>bookId</code><font><font>路徑參數,提取如下所示的信息:</font></font></p> + +<pre><code>app.get('/users/:userId/books/:bookId', function (req, res) { + // Access userId via: req.params.userId + // Access bookId via: req.params.bookId + res.send(req.params); +}) +</code></pre> + +<p><span style='background-color: #ffffff; color: #333333; display: inline !important; float: none; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; font-weight: 400; letter-spacing: normal; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'>路由參數的名稱,必須由“單詞字符”(AZ,az,0-9和_)組成。</span></p> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>注意:</font></font></strong><font><font><span> </span>URL<span> </span></font></font><em><font><font>/book/create</font></font></em><font><font>將與</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>/book/:bookId</code><font><font> 之類的路由匹配(它將提取要創建'<span> </span></font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>create</code><font><font>'的“bookId”值)。</font><font>將使用與傳入URL匹配的第一個路由,因此,如果要單獨處理</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>/book/create</code><font><font>URL,則必須在</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>/book/:bookId</code><font><font>路由之前,先定義其路由處理程序。</font></font></p> +</div> + +<p><font><font>這就是您開始使用路由所需的全部內容-如果需要,您可以在Express文檔中找到更多信息:</font></font><a class="external external-icon" href="http://expressjs.com/en/starter/basic-routing.html" rel="noopener" style='font-style: normal; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line; font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; background-color: rgb(255, 255, 255);'><font><font>基本路由</font></font></a><font><font>和</font></font><a class="external external-icon" href="http://expressjs.com/en/guide/routing.html" rel="noopener" style='font-style: normal; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line; font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; background-color: rgb(255, 255, 255);'><font><font>路由指南</font></font></a><font><font>。</font><font>以下部分顯示了我們如何為LocalLibrary設置路由和控制器。</font></font></p> + +<h2 id="本地圖書館需要的路由"><font><font>本地圖書館需要的路由</font></font></h2> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>下面列出了我們最終需要用於頁面的URL,其中object被替換為每個模型的名稱(book,bookinstance,genre,author),objects是對象的複數,id是默認情況下,為每個Mongoose模型實例指定的唯一實例字段(</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>_id</code><font><font>)。</font></font></p> + +<ul style='font-style: normal; margin: 0px 0px 24px; padding: 0px 0px 0px 40px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>catalog/</code><font><font><span> </span>— 主頁/索引頁面。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>catalog/<objects>/</code><font><font>—所有書本,書本實例,種類或作者的列表(例如/<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>catalog/books/</code><font><font>, /<span> </span></font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>catalog/genres/</code><font><font>等)</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>catalog/<object>/<em><id></em></code><font><font>—具有給定</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'><em>_id</em></code><font><font>字段值的特定書本,書本實例,種類或作者的詳細信息頁面(例如</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>/catalog/book/584493c1f4887f06c0e67d37</code><font><font>)。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>catalog/<object>/create</code><font><font>—用於創建新的書本,書本實例,種類或作者的表單(例如</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>/catalog/book/create</code><font><font>)。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>catalog/<object>/<em><id></em>/update</code><font><font>—使用給定的</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'><em>_id</em></code><font><font>字段值更新特定書本,書本實例,種類或作者的表單(例如</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>/catalog/book/584493c1f4887f06c0e67d37/update</code><font><font>)。</font></font></li> + <li style="font-style: normal !important; margin: 0px 0px 6px; padding: 0px; border: 0px;"><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>catalog/<object>/<em><id></em>/delete</code><font><font>—刪除具有給定</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'><em>_id</em></code><font><font>字段值的特定書本,書本實例,種類或作者的表單(例如</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>/catalog/book/584493c1f4887f06c0e67d37/delete</code><font><font>)。</font></font></li> +</ul> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>第一個主頁和列表頁面,不編碼任何其他信息。</font><font>雖然返回的結果,將取決於模型類型和數據庫中的內容,但為了獲取信息所運行的查詢,將始終相同(類似地,用於創建對象的代碼將始終類似)。</font><font>相反的,其他URL用於處理特定文檔/模型實例—這些將項目的標識編碼在URL中(如上面的</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'><em><id></em></code><font><font>)。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>我們將使用路徑參數,來提取編碼信息,並將其傳遞給路由處理程序(在稍後的文章中,我們將使用它來動態確定從數據庫獲取的信息)。</font><font>通過對我們的URL中的信息進行編碼,我們只需要一個路由,用於特定類型的每個資源(例如,一個路由來處理每個書本項目的顯示)。</font></font></p> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>注意</font></font></strong><font><font><span> </span>: Express允許您以任何方式構建URL -您可以在URL正文中編碼信息,就像上面一樣,或使用URL<span> </span></font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>GET</code><font><font>參數(例如</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>/book/?id=6</code><font><font>)。</font><font>無論您使用哪種方法,URL都應保持乾淨,合理且可讀(請在此處查看</font></font><a class="external external-icon" href="https://www.w3.org/Provider/Style/URI" rel="noopener" style='font-style: normal; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 18px; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; background-color: rgb(255, 243, 212);'><font><font>W3C建議</font></font></a><font><font>)。</font></font></p> +</div> + +<p><span style='background-color: #ffffff; color: #333333; display: inline !important; float: none; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; font-weight: 400; letter-spacing: normal; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'>接下來,我們為所有上述URL,創建路由處理程序回調函數和路由代碼。</span></p> + +<h2 id="創建路由-handler回調函式"><font><font>創建路由-handler回調函式</font></font></h2> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>在我們定義路由之前,我們將首先創建它們將調用的所有虛擬/骨架回調函數。</font><font>回調將存在Books,BookInstances,Genres 和Authors 的單獨“控制器” 模塊中(您可以使用任何文件/模塊結構,但這似乎是該項目的適當粒度)。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>首先在項目根目錄(</font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>/controllers</font></font></strong><font><font>)中,為我們的控制器創建一個文件夾,然後創建單獨的控制器文件/模塊,來處理每個模型:</font></font></p> + +<pre>/express-locallibrary-tutorial //the project root + <strong>/controllers</strong> + <strong>authorController.js</strong> + <strong>bookController.js</strong> + <strong>bookinstanceController.js</strong> + <strong>genreController.js</strong></pre> + +<h3 id="作者控制器"><span class="highlight-span" style="background-color: #333333; border: 0px; color: #ffffff; font-style: normal !important; font-weight: 400; line-height: 1.25; margin: 0px; padding: 0px 4px 0px 40px;"><font><font>作者控制器</font></font></span></h3> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>打開</font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>/controllers/authorController.js</font></font></strong><font><font>文件,並複制以下代碼:</font></font></p> + +<pre class="brush: js">var Author = require('../models/author'); + +// Display list of all Authors. +exports.author_list = function(req, res) { + res.send('NOT IMPLEMENTED: Author list'); +}; + +// Display detail page for a specific Author. +exports.author_detail = function(req, res) { + res.send('NOT IMPLEMENTED: Author detail: ' + req.params.id); +}; + +// Display Author create form on GET. +exports.author_create_get = function(req, res) { + res.send('NOT IMPLEMENTED: Author create GET'); +}; + +// Handle Author create on POST. +exports.author_create_post = function(req, res) { + res.send('NOT IMPLEMENTED: Author create POST'); +}; + +// Display Author delete form on GET. +exports.author_delete_get = function(req, res) { + res.send('NOT IMPLEMENTED: Author delete GET'); +}; + +// Handle Author delete on POST. +exports.author_delete_post = function(req, res) { + res.send('NOT IMPLEMENTED: Author delete POST'); +}; + +// Display Author update form on GET. +exports.author_update_get = function(req, res) { + res.send('NOT IMPLEMENTED: Author update GET'); +}; + +// Handle Author update on POST. +exports.author_update_post = function(req, res) { + res.send('NOT IMPLEMENTED: Author update POST'); +}; +</pre> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>該模塊首先導入我們稍後將使用的模型,來訪問和更新我們的數據。</font><font>然後它為我們希望處理的每個URL,導出函數(創建,更新和刪除操作使用表單,因此還有其他方法,來處理表單發布請求- 我們將在稍後的“表單文章” 中討論這些方法) 。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>所有函數都具有Express中間件函數的標準形式,如果方法沒有完成請求週期,則會調用請求,響應和</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>next</code><font><font>下一個函數的參數(在所有這些情況下,它都會執行!)。</font><font>這些方法只返回一個字符串,表明尚未創建關聯的頁面。</font><font>如果期望控制器函數接收路徑參數,則在消息字符串中,輸出這些參數(參見上面的</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>req.params.id</code><font><font>)。</font></font></p> + +<h4 id="書本實例控制器" style='font-style: normal; line-height: 1.2; margin: 30px 0px 20px; padding: 0px; border: 0px; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 1.375rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>書本實例控制器</font></font></h4> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>打開</font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>/controllers/bookinstanceController.js</font></font></strong><font><font>文件,並將其複製到以下代碼中(它遵循與</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>Author</code><font><font>控制器模塊相同的模式):</font></font></p> + +<pre class="brush: js">var BookInstance = require('../models/bookinstance'); + +// Display list of all BookInstances. +exports.bookinstance_list = function(req, res) { + res.send('NOT IMPLEMENTED: BookInstance list'); +}; + +// Display detail page for a specific BookInstance. +exports.bookinstance_detail = function(req, res) { + res.send('NOT IMPLEMENTED: BookInstance detail: ' + req.params.id); +}; + +// Display BookInstance create form on GET. +exports.bookinstance_create_get = function(req, res) { + res.send('NOT IMPLEMENTED: BookInstance create GET'); +}; + +// Handle BookInstance create on POST. +exports.bookinstance_create_post = function(req, res) { + res.send('NOT IMPLEMENTED: BookInstance create POST'); +}; + +// Display BookInstance delete form on GET. +exports.bookinstance_delete_get = function(req, res) { + res.send('NOT IMPLEMENTED: BookInstance delete GET'); +}; + +// Handle BookInstance delete on POST. +exports.bookinstance_delete_post = function(req, res) { + res.send('NOT IMPLEMENTED: BookInstance delete POST'); +}; + +// Display BookInstance update form on GET. +exports.bookinstance_update_get = function(req, res) { + res.send('NOT IMPLEMENTED: BookInstance update GET'); +}; + +// Handle bookinstance update on POST. +exports.bookinstance_update_post = function(req, res) { + res.send('NOT IMPLEMENTED: BookInstance update POST'); +}; +</pre> + +<h4 id="種類控制器" style='font-style: normal; line-height: 1.2; margin: 30px 0px 20px; padding: 0px; border: 0px; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 1.375rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>種類控制器</font></font></h4> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>打開</font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>/controllers/genreController.js</font></font></strong><font><font>文件,並複制以下文本(這與</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>Author</code><font><font>和</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>BookInstance</code><font><font>文件的模式相同):</font></font></p> + +<pre class="brush: js">var Genre = require('../models/genre'); + +// Display list of all Genre. +exports.genre_list = function(req, res) { + res.send('NOT IMPLEMENTED: Genre list'); +}; + +// Display detail page for a specific Genre. +exports.genre_detail = function(req, res) { + res.send('NOT IMPLEMENTED: Genre detail: ' + req.params.id); +}; + +// Display Genre create form on GET. +exports.genre_create_get = function(req, res) { + res.send('NOT IMPLEMENTED: Genre create GET'); +}; + +// Handle Genre create on POST. +exports.genre_create_post = function(req, res) { + res.send('NOT IMPLEMENTED: Genre create POST'); +}; + +// Display Genre delete form on GET. +exports.genre_delete_get = function(req, res) { + res.send('NOT IMPLEMENTED: Genre delete GET'); +}; + +// Handle Genre delete on POST. +exports.genre_delete_post = function(req, res) { + res.send('NOT IMPLEMENTED: Genre delete POST'); +}; + +// Display Genre update form on GET. +exports.genre_update_get = function(req, res) { + res.send('NOT IMPLEMENTED: Genre update GET'); +}; + +// Handle Genre update on POST. +exports.genre_update_post = function(req, res) { + res.send('NOT IMPLEMENTED: Genre update POST'); +}; +</pre> + +<h4 id="書本控制器" style='font-style: normal; line-height: 1.2; margin: 30px 0px 20px; padding: 0px; border: 0px; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 1.375rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>書本控制器</font></font></h4> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>打開</font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>/controllers/bookController.js</font></font></strong><font><font>文件,並複制以下代碼。</font><font>它遵循與其他控制器模塊相同的模式,但另外還有一個</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>index()</code><font><font>函數,用於顯示站點歡迎頁面:</font></font></p> + +<pre class="brush: js">var Book = require('../models/book'); + +<strong>exports.index = function(req, res) { + res.send('NOT IMPLEMENTED: Site Home Page'); +};</strong> + +// Display list of all books. +exports.book_list = function(req, res) { + res.send('NOT IMPLEMENTED: Book list'); +}; + +// Display detail page for a specific book. +exports.book_detail = function(req, res) { + res.send('NOT IMPLEMENTED: Book detail: ' + req.params.id); +}; + +// Display book create form on GET. +exports.book_create_get = function(req, res) { + res.send('NOT IMPLEMENTED: Book create GET'); +}; + +// Handle book create on POST. +exports.book_create_post = function(req, res) { + res.send('NOT IMPLEMENTED: Book create POST'); +}; + +// Display book delete form on GET. +exports.book_delete_get = function(req, res) { + res.send('NOT IMPLEMENTED: Book delete GET'); +}; + +// Handle book delete on POST. +exports.book_delete_post = function(req, res) { + res.send('NOT IMPLEMENTED: Book delete POST'); +}; + +// Display book update form on GET. +exports.book_update_get = function(req, res) { + res.send('NOT IMPLEMENTED: Book update GET'); +}; + +// Handle book update on POST. +exports.book_update_post = function(req, res) { + res.send('NOT IMPLEMENTED: Book update POST'); +}; +</pre> + +<h2 id="創建目錄路由模組"><font><font>創建目錄路由模組</font></font></h2> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>接下來,我們為LocalLibrary 網站,創建所需全部URL 的路由,這將調用我們在上一節中定義的控制器功能。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>骨架網站已經有一個</font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>./routes</font></font></strong><font><font>文件夾,其中包含索引和用戶的路由。</font><font>在此文件夾中,創建另一個路徑文件—<span> </span></font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>catalog.js</font></font></strong><font><font><span> </span>—如下圖所示。</font></font></p> + +<pre>/express-locallibrary-tutorial //the project root + /routes + index.js + users.js + <strong>catalog.js</strong></pre> + +<p><font><font>打開</font></font><strong style='background-color: #ffffff; border: 0px; color: #333333; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>/routes/<span> </span></font></font></strong><strong style='background-color: #ffffff; border: 0px; color: #333333; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>catalog.js</font></font></strong><font><font>,複製下面的代碼:</font></font></p> + +<pre class="brush: js"><strong>var express = require('express'); +var router = express.Router(); +</strong> +// Require controller modules. +var book_controller = require('../controllers/bookController'); +var author_controller = require('../controllers/authorController'); +var genre_controller = require('../controllers/genreController'); +var book_instance_controller = require('../controllers/bookinstanceController'); + +/// BOOK ROUTES /// + +// GET catalog home page. +router.get('/', book_controller.index); + +// GET request for creating a Book. NOTE This must come before routes that display Book (uses id). +router.get('/book/create', book_controller.book_create_get); + +// POST request for creating Book. +router.post('/book/create', book_controller.book_create_post); + +// GET request to delete Book. +router.get('/book/:id/delete', book_controller.book_delete_get); + +// POST request to delete Book. +router.post('/book/:id/delete', book_controller.book_delete_post); + +// GET request to update Book. +router.get('/book/:id/update', book_controller.book_update_get); + +// POST request to update Book. +router.post('/book/:id/update', book_controller.book_update_post); + +// GET request for one Book. +router.get('/book/:id', book_controller.book_detail); + +// GET request for list of all Book items. +router.get('/books', book_controller.book_list); + +/// AUTHOR ROUTES /// + +// GET request for creating Author. NOTE This must come before route for id (i.e. display author). +router.get('/author/create', author_controller.author_create_get); + +// POST request for creating Author. +router.post('/author/create', author_controller.author_create_post); + +// GET request to delete Author. +router.get('/author/:id/delete', author_controller.author_delete_get); + +// POST request to delete Author. +router.post('/author/:id/delete', author_controller.author_delete_post); + +// GET request to update Author. +router.get('/author/:id/update', author_controller.author_update_get); + +// POST request to update Author. +router.post('/author/:id/update', author_controller.author_update_post); + +// GET request for one Author. +router.get('/author/:id', author_controller.author_detail); + +// GET request for list of all Authors. +router.get('/authors', author_controller.author_list); + +/// GENRE ROUTES /// + +// GET request for creating a Genre. NOTE This must come before route that displays Genre (uses id). +router.get('/genre/create', genre_controller.genre_create_get); + +//POST request for creating Genre. +router.post('/genre/create', genre_controller.genre_create_post); + +// GET request to delete Genre. +router.get('/genre/:id/delete', genre_controller.genre_delete_get); + +// POST request to delete Genre. +router.post('/genre/:id/delete', genre_controller.genre_delete_post); + +// GET request to update Genre. +router.get('/genre/:id/update', genre_controller.genre_update_get); + +// POST request to update Genre. +router.post('/genre/:id/update', genre_controller.genre_update_post); + +// GET request for one Genre. +router.get('/genre/:id', genre_controller.genre_detail); + +// GET request for list of all Genre. +router.get('/genres', genre_controller.genre_list); + +/// BOOKINSTANCE ROUTES /// + +// GET request for creating a BookInstance. NOTE This must come before route that displays BookInstance (uses id). +router.get('/bookinstance/create', book_instance_controller.bookinstance_create_get); + +// POST request for creating BookInstance. +router.post('/bookinstance/create', book_instance_controller.bookinstance_create_post); + +// GET request to delete BookInstance. +router.get('/bookinstance/:id/delete', book_instance_controller.bookinstance_delete_get); + +// POST request to delete BookInstance. +router.post('/bookinstance/:id/delete', book_instance_controller.bookinstance_delete_post); + +// GET request to update BookInstance. +router.get('/bookinstance/:id/update', book_instance_controller.bookinstance_update_get); + +// POST request to update BookInstance. +router.post('/bookinstance/:id/update', book_instance_controller.bookinstance_update_post); + +// GET request for one BookInstance. +router.get('/bookinstance/:id', book_instance_controller.bookinstance_detail); + +// GET request for list of all BookInstance. +router.get('/bookinstances', book_instance_controller.bookinstance_list); + +<strong>module.exports = router;</strong> +</pre> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>該模塊導入Express,然後使用它來創建一個</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>Router</code><font><font>對象。</font><font>路由都在路由器上設置完成,然後導出。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>路由是使用路由器對像上的</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>.get()</code><font><font>或</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>.post()</code><font><font>方法定義的。</font><font>所有路徑都是使用字符串定義的(我們不使用字符串模式或正則表達式)。</font><font>作用於某些特定資源(如書籍)的路由,則使用路徑參數從URL中獲取對象標識id。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>處理程序函數,都是從我們在上一節中,創建的控制器模塊導入的。</font></font></p> + +<h3 id="更新_index_路由模組"><span class="highlight-span" style="background-color: #333333; border: 0px; color: #ffffff; font-style: normal !important; font-weight: 400; line-height: 1.25; margin: 0px; padding: 0px 4px 0px 40px;">更新 index 路由模組</span></h3> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>我們已經設置了所有新路由,但我們仍然有一個到原始頁面的路由。</font><font>讓我們將其重定向,到我們在路徑'/ catalog' 創建的新索引頁面。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>打開</font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>/routes/index.js</font></font></strong><font><font>並使用下面的函數,替換現有路由。</font></font></p> + +<pre class="brush: js">// GET home page. +router.get('/', function(req, res) { + res.redirect('/catalog'); +});</pre> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>注意:</font></font></strong><font><font>這是我們第一次使用</font></font><a class="external external-icon" href="https://expressjs.com/en/4x/api.html#res.redirect" rel="noopener" style='font-style: normal; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; white-space: pre-line; font-family: x-locale-heading-primary, zillaslab, Palatino, "Palatino Linotype", x-locale-heading-secondary, serif; font-size: 18px; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; background-color: rgb(255, 243, 212);'><font><font>redirect()</font></font></a><font><font>響應方法。</font><font>這會重定向到指定的頁面,默認情況下會發送HTTP狀態代碼“302 Found”。</font><font>您可以根據需要,更改返回的狀態代碼,並提供絕對路徑或相對路徑。</font></font></p> +</div> + +<h3 id="更新app.js"><span class="highlight-span" style="background-color: #333333; border: 0px; color: #ffffff; font-style: normal !important; font-weight: 400; line-height: 1.25; margin: 0px; padding: 0px 4px 0px 40px;"><font><font>更新app.js</font></font></span></h3> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>最後一步,是將路由,添加到中間件鏈。</font><font>我們在</font></font><code style='font-style: inherit; margin: 0px; padding: 0px 2px; border: 0px; font-weight: inherit; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word;'>app.js</code><font><font>這樣做。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>打開</font></font><strong style="border: 0px; font-style: normal !important; margin: 0px; padding: 0px;"><font><font>app.js</font></font></strong><font><font>,並要求其他路由下方的目錄路由(添加下面顯示的第三行,在其他兩個路由下面):</font></font></p> + +<pre class="brush: js">var indexRouter = require('./routes/index'); +var usersRouter = require('./routes/users'); +<strong>var catalogRouter = require('./routes/catalog'); //Import routes for "catalog" area of site</strong></pre> + +<p><span style='background-color: #ffffff; color: #333333; display: inline !important; float: none; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; font-weight: 400; letter-spacing: normal; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'>接下來,將目錄路由,添加到其他路由下面的中間件堆棧(添加下面顯示的第三行,在其他兩行下面):</span></p> + +<pre class="brush: js">app.use('/', indexRouter); +app.use('/users', usersRouter); +<strong>app.use('/catalog', catalogRouter); // Add catalog routes to middleware chain.</strong></pre> + +<div class="note"> +<p><strong style='background-color: #fff3d4; border: 0px; color: #333333; font-family: x-locale-heading-primary,zillaslab,Palatino,"Palatino Linotype",x-locale-heading-secondary,serif; font-size: 18px; font-style: normal; font-weight: 700; letter-spacing: normal; margin: 0px; padding: 0px; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'><font><font>Note:</font></font></strong><font><font><span> </span> 我們已在路徑</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>'/catalog'</code><font><font>中添加了目錄模塊。</font><font>它預先添加到目錄模塊中定義的所有路徑。</font><font>例如,要訪問書本列表,URL將為:</font></font><code style='font-style: normal; margin: 0px; padding: 0px 2px; border: 0px; font-weight: 400; background-color: rgba(220, 220, 220, 0.5); border-radius: 2px; font-family: consolas, "Liberation Mono", courier, monospace; word-wrap: break-word; font-size: 1rem; color: rgb(51, 51, 51); letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; text-decoration-style: initial;'>/catalog/books/</code><font><font>。</font></font></p> +</div> + +<p><font>就是這樣。</font><font>現在應該為我們最終在LocalLibrary 網站上支持的所有URL,啟用路由和框架功能。</font></p> + +<h3 id="測試路由"><span class="highlight-span" style="background-color: #333333; border: 0px; color: #ffffff; font-style: normal !important; font-weight: 400; line-height: 1.25; margin: 0px; padding: 0px 4px 0px 40px;"><font><font>測試路由</font></font></span></h3> + +<p><span style='background-color: #ffffff; color: #333333; display: inline !important; float: none; font-family: "Open Sans",arial,x-locale-body,sans-serif; font-size: medium; font-style: normal; font-weight: 400; letter-spacing: normal; text-align: start; text-decoration-style: initial; text-indent: 0px; text-transform: none; white-space: normal;'>要測試路由,首先使用您通常的方法啟動網站</span></p> + +<ul> + <li>預設方法 + <pre class="brush: bash"><code>// Windows +SET DEBUG=express-locallibrary-tutorial:* & npm start + +// macOS or Linux +DEBUG=express-locallibrary-tutorial:* npm start</code> +</pre> + </li> + <li><font><font>如果您先前設置了</font></font><a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website" style='font-style: normal; text-decoration: none; color: rgb(63, 135, 166); margin: 0px; padding: 0px; border: 0px; font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: left; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255);'><font><font>nodemon</font></font></a><font><font><span> </span>,則可以使用:</font></font> + <pre><code>// Windows +SET DEBUG=express-locallibrary-tutorial:* & npm <strong>run devstart</strong> + +// macOS or Linux +</code>DEBUG=express-locallibrary-tutorial:* npm <strong style="font-family: inherit; font-size: 1rem;">run devstart</strong> +</pre> + </li> +</ul> + +<p><font>然後瀏覽一些上面的LocalLibrary URL,並驗證您沒有收到錯誤頁面(HTTP 404)。</font><font>為方便起見,下面列出了一小組網址:</font></p> + +<ul> + <li><a href="http://localhost:3000/">http://localhost:3000/</a></li> + <li><a href="http://localhost:3000/catalog">http://localhost:3000/catalog</a></li> + <li><a href="http://localhost:3000/catalog/books">http://localhost:3000/catalog/books</a></li> + <li><a href="http://localhost:3000/catalog/bookinstances/">http://localhost:3000/catalog/bookinstances/</a></li> + <li><a href="http://localhost:3000/catalog/authors/">http://localhost:3000/catalog/authors/</a></li> + <li><a href="http://localhost:3000/catalog/genres/">http://localhost:3000/catalog/genres/</a></li> + <li><a href="http://localhost:3000/catalog/book/5846437593935e2f8c2aa226/">http://localhost:3000/catalog/book/5846437593935e2f8c2aa226</a></li> + <li><a href="http://localhost:3000/catalog/book/create">http://localhost:3000/catalog/book/create</a></li> +</ul> + +<h2 id="總結"><font><font>總結</font></font></h2> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>我們現在為網站創建了所有的路由,在稍後的教程,我們可以將實作完成的代碼,填入到空殼控制器函式。</font><font>以這樣的方式,我們學到了許多關於Express 路由的基本信息,以及一些組織路由和控制器的方式。</font></font></p> + +<p style='font-style: normal; margin: 0px 0px 24px; padding: 0px; border: 0px; max-width: 42rem; color: rgb(51, 51, 51); font-family: "Open Sans", arial, x-locale-body, sans-serif; font-size: medium; font-weight: 400; letter-spacing: normal; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; background-color: rgb(255, 255, 255); text-decoration-style: initial;'><font><font>下一篇文章,我們將使用視圖(模板) 和存在模型裡的信息,為網站創建一個合適的歡迎頁面。</font></font></p> + +<h2 id="參閱">參閱</h2> + +<ul> + <li><a href="http://expressjs.com/en/starter/basic-routing.html">Basic routing</a> (Express docs)</li> + <li><a href="http://expressjs.com/en/guide/routing.html">Routing guide</a> (Express docs)</li> +</ul> + +<p>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs/Displaying_data", "Learn/Server-side/Express_Nodejs")}}</p> + +<p> </p> + +<h2 id="本教程連結">本教程連結</h2> + +<ul> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node introduction</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">Setting up a Node (Express) development environment</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Express Tutorial: The Local Library website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Express Tutorial Part 2: Creating a skeleton website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Express Tutorial Part 3: Using a Database (with Mongoose)</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/routes">Express Tutorial Part 4: Routes and controllers</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/deployment">Express Tutorial Part 7: Deploying to production</a></li> +</ul> + +<p> </p> diff --git a/files/zh-tw/learn/server-side/express_nodejs/skeleton_website/index.html b/files/zh-tw/learn/server-side/express_nodejs/skeleton_website/index.html new file mode 100644 index 0000000000..0139a30dd9 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/skeleton_website/index.html @@ -0,0 +1,506 @@ +--- +title: 'Express 教學 2: 創建一個骨架網站' +slug: Learn/Server-side/Express_Nodejs/skeleton_website +translation_of: Learn/Server-side/Express_Nodejs/skeleton_website +--- +<div>{{LearnSidebar}}</div> + +<p>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs")}}</p> + +<p class="summary">在 <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Express 教程</a>的第二篇文章,演示如何創建一個 "骨架" 網站項目,你可以接著在裡面加入網站特定的路由、模板/視圖、和數据庫調用。</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">前置條件:</th> + <td><a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">架設一個Node 開發環境</a>。回顧Express 教程。</td> + </tr> + <tr> + <th scope="row">目標:</th> + <td>能夠使用<em>Express 應用產生器,</em>創建自己新的網頁項目。</td> + </tr> + </tbody> +</table> + +<h2 id="概覽">概覽</h2> + +<p>本文演示如何使用 <a class="external external-icon" href="https://expressjs.com/en/starter/generator.html" rel="noopener">Express 應用產生器</a> 工具,創建一個 "骨架" 網站,然後您可以使用特定於站點的路由,視圖/模板和數據庫調用來填充它們。在這個教程,我們將使用該工具,為我們的本地圖書館網站創建框架,我們稍後將添加該網站所需的所有其他代碼。該過程非常簡單,只需要在命令行上,用新項目名稱調用生成器,還可以指定站點的模板引擎和 CSS 生成器。</p> + +<p>以下部分向您展示如何調用應用程序生成器,並提供關於視圖或CSS的不同選項的一些解釋。我們還將解釋骨架網站的結構。最後,我們將展示如何運行網站,來驗證它是否有效。</p> + +<div class="note"> +<p><span style="line-height: 1.5;"><strong>注意</strong>: </span>Express Application Generator並非 Express 應用程序的唯一生成器,生成的項目不是構建文件和目錄的唯一可行方式。然而,生成的網站具有易於擴展和理解的模塊化結構。有關最小 Express 應用程序的信息,請參閱 <span style="line-height: 1.5;"><a href="https://expressjs.com/en/starter/hello-world.html">Hello world </a></span>示例(Express docs)。</p> +</div> + +<h2 id="使用應用產生器">使用應用產生器</h2> + +<p>您應該已經安裝了生成器,作為設置 Node 開發環境的一部分。作為快速提醒,您可以使用 NPM 軟件包管理器,在整個站點安裝生成器工具,如下所示:</p> + +<pre class="brush: bash notranslate"><code>npm install express-generator -g</code></pre> + +<p>生成器有許多選項,您可以使用<code>--help</code>(或<code>-h</code>)命令,在命令行上查看它們:</p> + +<pre class="brush: bash notranslate">> express --help + + Usage: express [options] [dir] + + Options: + + -h, --help output usage information + --version output the version number + -e, --ejs add ejs engine support + --pug add pug engine support + --hbs add handlebars engine support + -H, --hogan add hogan.js engine support + -v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade) + -c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css) + --git add .gitignore + -f, --force force on non-empty directory +</pre> + +<p>您可以使用 Jade 視圖引擎和純 CSS 來指定 <code>express</code>,以在當前目錄中創建項目(如果指定目錄名,則項目將創建在具有該名稱的子文件夾中)。</p> + +<pre class="brush: bash notranslate"><code>express</code></pre> + +<p>您還可以使用<code>--view</code>選擇視圖(模板)引擎,並且/或者使用<code>--css</code>選擇 CSS 生成引擎。</p> + +<div class="note"> +<p><strong>注意:</strong> 選擇模板引擎的其他選項(例如 <code>--hogan</code>, <code>--ejs</code>, <code>--hbs</code>等)已被棄用。請用 <code>--view</code> (或 <code>-v</code>)!</p> +</div> + +<h3 id="我應該用哪個視圖引擎">我應該用哪個視圖引擎?</h3> + +<p>Express Application Generator 允許您配置許多流行的視圖/模板引擎,包括 <a href="https://www.npmjs.com/package/ejs">EJS</a>, <a href="http://github.com/donpark/hbs">Hbs</a>, <a href="https://pugjs.org/api/getting-started.html">Pug</a> (Jade), <a href="https://www.npmjs.com/package/twig">Twig</a>, 和 <a href="https://www.npmjs.com/package/vash">Vash</a>,但如果您沒有指定視圖選項,它會默認選擇Jade。 Express 本身也可以支持大量其他模板語言,是「<a href="https://github.com/expressjs/express/wiki#template-engines">開箱即可使用</a>」的。</p> + +<div class="note"> +<p><strong>注意:</strong> 如果要使用生成器不支持的模板引擎,請參閱<a href="https://expressjs.com/en/guide/using-template-engines.html">在Express中使用模板引擎(Express文檔)</a>,並參閱目標視圖引擎的文檔。</p> +</div> + +<p>一般來說,您應該選擇一種「可以提供您所需的所有功能」的模板引擎,<br> + 並使您能夠儘早提高生產力 - 換句話說,就像您選擇其他組件一樣!比較模板引擎時需要考慮的一些事項如下:</p> + +<ul> + <li>具備生產力之前所需要花費的時間 — 如果您的團隊已經有模板語言的經驗,那麼使用該語言可能會更快地提高生產力。如果不是,那麼你應該考慮候選模板引擎的相對學習曲線(即以投入時間與得到的生產力為XY座標所繪製的曲線)。</li> + <li>人氣和活躍 — 回顧引擎的普及程度以及它是否擁有活躍的社區。當您在網站的生命週期中遇到問題時,能夠獲得對引擎的支持非常重要。</li> + <li>風格 — 某些模板引擎使用特定的標記,來指示在 “普通” HTML內插入的內容,而其他模板引擎使用不同的語法(例如,使用縮進和區塊名稱)構造HTML。</li> + <li>性能/渲染時間。</li> + <li>特點 — 你應該考慮你看中的引擎是否具有以下功能: + <ul> + <li>佈局繼承:允許您定義基本模板,然後 “繼承” 它的一部分,使特定頁面可以有不同的呈現。比起通過包含大量必需組件,或每次從頭開始構建模板,這通常是更好的方式。</li> + <li>"Include" 支持:允許您通過包含其他模板,來構建模板。</li> + <li>簡潔的變量和循環控制語法。</li> + <li>能夠在模板級別過濾變量值(例如,將變量設置為大寫,或格式化日期值)。</li> + <li>能夠生成HTML以外的輸出格式(例如 JSON 或 XML)。</li> + <li>支持異步操作和流媒體。</li> + <li>可以在客戶端和服務器上使用。如果可以在客戶端上使用模板引擎,則允許提供數據,並有可能在客戶端完成所有渲染,或大部分渲染。</li> + </ul> + </li> +</ul> + +<div class="note"> +<p><strong>提示:</strong> 互聯網上有許多資源,可幫助您比較不同的視圖/模板引擎選擇!</p> +</div> + +<p>對於這個項目,我們將使用 <a href="https://pugjs.org/api/getting-started.html">Pug</a> 模板引擎(這是最近更名的 Jade 引擎),因為這是最流行的 Express / JavaScript 模板語言之一,並且應用發生器支持開箱即用。</p> + +<h3 id="我應該用哪個CSS樣式引擎">我應該用哪個CSS樣式引擎?</h3> + +<p>Express 應用生成器允許您創建一個項目,並配置最常見的 CSS 樣式表引擎:<a href="http://lesscss.org/">LESS</a>, <a href="http://sass-lang.com/">SASS</a>, <a href="http://compass-style.org/">Compass</a>, <a href="http://stylus-lang.com/">Stylus</a>。</p> + +<div class="note"> +<p><strong>注意: </strong>CSS有一些限制,使某些任務變得困難。 CSS 樣式表引擎允許您使用更強大的語法來定義您的 CSS,然後將定義編譯為純粹的舊式 CSS,以供瀏覽器使用。</p> +</div> + +<p>與模板引擎一樣,您應該使用樣式表引擎,這樣可以讓您的團隊獲得最高生產力。對於這個項目,我們將使用普通的 CSS(默認值),因為我們的 CSS 要求不夠複雜,沒有必要使用其他任何東西。</p> + +<h3 id="我應該用哪個數據庫">我應該用哪個數據庫?</h3> + +<p>生成的代碼不使用/包含任何數據庫。 Express 應用程序可以使用 Node支持的任何<a href="https://expressjs.com/en/guide/database-integration.html">數據庫機制</a>(Express 本身並未針對數據庫管理,定義任何特定的附加行為/要求)。<br> + 我們將在後面的文章中,討論如何與數據庫集成。</p> + +<h2 id="創建項目">創建項目</h2> + +<p>對於我們要構建的示例 Local Library 應用程序,我們將使用 Pug 模板庫,創建一個名為 express-locallibrary-tutorial 的項目,並且不使用 CSS樣式表引擎。</p> + +<p>首先到要創建項目的位置,然後在命令提示符下,運行 Express 應用生成器,如下所示:</p> + +<pre class="brush: bash notranslate">express express-locallibrary-tutorial --view=pug +</pre> + +<p>成器將創建(並列出)項目的文件。</p> + +<pre class="brush: bash notranslate"> create : express-locallibrary-tutorial + create : express-locallibrary-tutorial/package.json + create : express-locallibrary-tutorial/app.js + create : express-locallibrary-tutorial/public/images + create : express-locallibrary-tutorial/public + create : express-locallibrary-tutorial/public/stylesheets + create : express-locallibrary-tutorial/public/stylesheets/style.css + create : express-locallibrary-tutorial/public/javascripts + create : express-locallibrary-tutorial/routes + create : express-locallibrary-tutorial/routes/index.js + create : express-locallibrary-tutorial/routes/users.js + create : express-locallibrary-tutorial/views + create : express-locallibrary-tutorial/views/index.pug + create : express-locallibrary-tutorial/views/layout.pug + create : express-locallibrary-tutorial/views/error.pug + create : express-locallibrary-tutorial/bin + create : express-locallibrary-tutorial/bin/www + + install dependencies: + > cd express-locallibrary-tutorial && npm install + + run the app: + > SET DEBUG=express-locallibrary-tutorial:* & npm start</pre> + +<p>在輸出結束時,生成器提供關於「如何安裝依賴關係」的指示信息(如 <strong>package.json </strong>文件中所列),以及如何運行應用程序(上述說明適用於 Windows;在 Linux / macOS上,它們會略有不同)。</p> + +<h2 id="運行骨架網站">運行骨架網站</h2> + +<p>在這一時間點上,我們有一個完整的骨架項目。該網站實際上並沒有做太多工作,但運行它,能夠展示它是如何工作的。</p> + +<ol> + <li>首先安裝依賴項(<code>install</code>安裝命令,將獲取項目的 <strong>package.json </strong>文件中列出的所有依賴項包)。 + + <pre class="brush: bash notranslate">cd express-locallibrary-tutorial +npm install</pre> + </li> + <li>然後運行該應用程序。 + <ul> + <li>在Windows上,使用此命令: + <pre class="brush: bash notranslate">SET DEBUG=express-locallibrary-tutorial:* & npm start</pre> + </li> + <li>在macOS 或 Linux,使用此命令: + <pre class="brush: bash notranslate">DEBUG=express-locallibrary-tutorial:* npm start +</pre> + </li> + </ul> + </li> + <li>然後在瀏覽器中加載 <a href="http://localhost:3000/">http://localhost:3000/</a> ,以訪問該應用程序。</li> +</ol> + +<p>你應該會看到一個瀏覽器頁面,就像這樣:</p> + +<p><img alt="Browser for default Express app generator website" src="https://mdn.mozillademos.org/files/14375/ExpressGeneratorSkeletonWebsite.png" style="display: block; height: 403px; margin: 0px auto; width: 576px;"></p> + +<p>你有一個能工作的 Express 應用了,讓它在 <a href="http://localhost:3000/">http://localhost:3000/ </a>服務。</p> + +<div class="note"> +<p><strong>注意:</strong> 您也可以使用 <code>npm start</code>命令啟動應用程序。如下圖所示,指定 DEBUG 變量可啟用控制台日誌記錄/調試。例如,當你訪問上面的頁面時,你會看到像這樣的調試輸出:</p> + +<pre class="brush: bash notranslate">>SET DEBUG=express-locallibrary-tutorial:* & npm start + +> express-locallibrary-tutorial@0.0.0 start D:\express-locallibrary-tutorial +> node ./bin/www + + express-locallibrary-tutorial:server Listening on port 3000 +0ms +GET / 200 288.474 ms - 170 +GET /stylesheets/style.css 200 5.799 ms - 111 +GET /favicon.ico 404 34.134 ms - 1335</pre> +</div> + +<h2 id="讓伺服器在檔案更改時重新啟動">讓伺服器在檔案更改時重新啟動</h2> + +<p>在您重新啟動服務器之前,您對 Express 網站所做的任何更改,目前都不可見。每次進行更改時,必須停止並重新啟動服務器,很快變得非常煩人,因此值得花時間使服務器在需要時,自動重新啟動。</p> + +<p>這種工具中,最簡單的之一就是 <a href="https://github.com/remy/nodemon">nodemon</a>。這通常是全局安裝的(因為它是一個“工具”),但在這裡,我們將在本地安裝和使用它,作為開發人員依賴項,以便任何使用該項目的開發人員,在安裝應用程序時自動獲取它。在骨架項目的根目錄中,使用以下命令:</p> + +<pre class="brush: bash notranslate">npm install --save-dev nodemon</pre> + +<p>如果您打開項目的 <strong>package.json</strong> 文件,您現在將看到一個具有此依賴關係的新區段:</p> + +<pre class="brush: json notranslate"> "devDependencies": { + "nodemon": "^1.14.11" + } +</pre> + +<p>由於該工具沒有全局安裝,我們無法從命令行啟動它(除非我們將其添加到路徑中),但是我們可以從 NPM 腳本中調用它,因為 NPM 知道所有關於安裝的軟件包的信息。找到你的 package.json 的腳本 scripts 區塊。我們更新 <code>scripts </code>區塊,最初的一行,以"<code>start</code>"開頭,在該行的末尾添加逗號,並添加 "<code>devstart</code>" 開頭的一行,如下所示:</p> + +<pre class="brush: json notranslate"> "scripts": { + "start": "node ./bin/www"<strong>,</strong> +<strong> "devstart": "nodemon ./bin/www"</strong> + }, +</pre> + + + +<p>現在我們可以用與前面幾乎完全相同的方式,啟動服務器,但使用指定的 devstart 命令:</p> + +<ul> + <li>在 Windows,使用此命令: + <pre class="brush: bash notranslate">SET DEBUG=express-locallibrary-tutorial:* & npm <strong>run devstart</strong></pre> + </li> + <li>在 macOS or Linux,使用此命令: + <pre class="brush: bash notranslate">DEBUG=express-locallibrary-tutorial:* npm <strong>run devstart</strong> +</pre> + </li> +</ul> + +<div class="note"> +<p><strong>注意:</strong> 現在,如果您編輯項目中的任何文件,服務器將重新啟動(或者您可以隨時在命令提示符下,鍵入<code>rs</code>來重新啟動它)。您仍需要重新加載瀏覽器,以刷新頁面。</p> + +<p>我們現在必須調用“<code>npm run <scriptname></code>”而不是 <code>npm start</code>,因為“start”實際上是映射到指定腳本的 NPM 命令。我們可以在啟動腳本中替換該命令,但我們只想在開發期間使用 nodemon,因此創建新的腳本命令是有意義的。</p> +</div> + +<h2 id="從產生器得到的項目">從產生器得到的項目</h2> + +<p>現在我們來看看我們剛剛創建的項目。</p> + +<h3 id="目錄結構">目錄結構</h3> + +<p>從產生器得到的生成項目,現在已經安裝了依賴項,具有以下文件結構 (<strong>不帶</strong>前綴 “/” 的項目,表示文件)。 <strong>package.json </strong>文件定義了應用程序依賴項,和其他信息。它還定義了一個啟動腳本,它將調用應用程序入口點 JavaScript 文件 <strong>/bin/www</strong>。這設置了一些應用程序的錯誤處理,然後加載 <strong>app.js</strong> ,來完成剩下的工作。應用程序路徑,存儲在 <strong>/routes </strong>目錄下的單獨模塊中。模板存儲在 <strong>/views</strong> 目錄下。</p> + +<pre class="notranslate">/express-locallibrary-tutorial + <strong>app.js</strong> + /bin + <strong>www</strong> + <strong>package.json</strong> + /node_modules + [about 4,500 subdirectories and files] + /public + /images + /javascripts + /stylesheets + <strong>style.css</strong> + /routes + <strong>index.js</strong> + <strong>users.js</strong> + /views + <strong>error.pug</strong> + <strong>index.pug</strong> + <strong>layout.pug</strong> + +</pre> + +<p>以下各節將詳細介紹這些文件。</p> + +<h3 id="package.json">package.json</h3> + +<p><strong>package.json </strong>文件定義了應用程序依賴關係,和其他訊息:</p> + +<pre class="brush: json notranslate">{ + "name": "express-locallibrary-tutorial", + "version": "0.0.0", + "private": true, + "scripts": { + "start": "node ./bin/www", + "devstart": "nodemon ./bin/www" + }, + "dependencies": { + "body-parser": "~1.18.2", + "cookie-parser": "~1.4.3", + "debug": "~2.6.9", + "express": "~4.16.2", + "morgan": "~1.9.0", + "pug": "~2.0.0-rc.4", + "serve-favicon": "~2.4.5" + }, + "devDependencies": { + "nodemon": "^1.14.11" + } +} +</pre> + +<p>依賴關係包括 express 套件,和我們所選視圖引擎(pug)的套件。另外,我們還有以下的套件,在許多 Web 應用程序中很有用:</p> + +<ul> + <li><a href="https://www.npmjs.com/package/body-parser">body-parser</a>: 這解析傳入HTTP請求的正文 body 部分,並更容易提取包含信息的不同部分。例如,您可以使用它來讀取 <code>POST</code> 參數。</li> + <li><a href="https://www.npmjs.com/package/cookie-parser">cookie-parser</a>: 用於解析 cookie header 並填充 <code>req.cookies</code>(本質上提供了訪問 cookie 信息的便捷方法)。</li> + <li><a href="https://www.npmjs.com/package/debug">debug</a>: 一個小型 node 調試程序,仿照 node 核心的調試技術建立的。</li> + <li><a href="https://www.npmjs.com/package/morgan">morgan</a>: 搭配 node 使用的 HTTP 請求記錄器中間層軟件。</li> + <li><a href="https://www.npmjs.com/package/serve-favicon">serve-favicon</a>: 用於提供收藏圖標 <a href="https://en.wikipedia.org/wiki/Favicon">favicon</a> 的 node 中間層軟件(這是用於表示瀏覽器選項卡、書籤等網站內的圖標)。</li> +</ul> + +<p>腳本部分,定義了一個“開始” "start" 腳本,當我們調用 <code>npm start</code> 來啟動服務器時,這就是我們所調用的腳本。從腳本定義中,您可以看到這實際上用 node 啟動了 JavaScript 文件 <strong>./bin/www</strong>。它還定義了一個“devstart” 腳本,我們在調用 <code>npm run devstart </code>時調用它。這將啟動相同的 <strong>./bin/www </strong>文件,但使用 nodemon 調用而不是 node 。</p> + +<pre class="brush: json notranslate"> "scripts": { + "start": "node ./bin/www", + "devstart": "nodemon ./bin/www" + }, +</pre> + +<h3 id="www_文件">www 文件</h3> + +<p>文件 <strong>/bin/www</strong> 是應用程序入口點!它做的第一件事是 <code>require()</code> “真正的” 應用程序入口點(即項目根目錄中的 app.js ),<strong>app.js </strong>會設置並返回 <code><a href="http://expressjs.com/en/api.html">express()</a></code>應用程序的對象。</p> + +<pre class="brush: js notranslate">#!/usr/bin/env node + +/** + * Module dependencies. + */ + +<strong>var app = require('../app');</strong> +</pre> + +<div class="note"> +<p><strong>注意:</strong> <code>require()</code> 是一個全局 node 函數,用於將模塊導入當前文件。這裡我們使用相對路徑指定 <strong>app.js</strong> 模塊,並省略可選的(<strong>.js</strong>)文件擴展名。</p> +</div> + +<p>此文件中的其餘代碼,將設置一個node 運行的HTTP 服務器,並將應用app 設置為特定的端口(在環境變量中定義,如果變量未定義,則定義為3000),並開始監聽和報告服務器錯誤和連接。現在你並不需要知道代碼的其他內容(這個文件中的所有內容都是 “樣板文件” ),但如果你感興趣,可以隨時查看它。</p> + +<h3 id="app.js">app.js</h3> + +<p>此文件創建一個 <code>express</code> 應用程序對象(按傳統命名為 <code>app</code>),使用各種設置和中間件,以設置應用程序,然後從模塊導出應用程序。下面的代碼只顯示了文件的一部分,創建和導出應用程序對象的部分:</p> + +<pre class="brush: js notranslate"><code>var express = require('express'); +var app = express(); +... +</code>module.exports = app; +</pre> + +<p>回到上面的 <strong>www</strong> 入口點文件,它是在導入該文件時,提供給調用者的這個 <code>module.exports</code> 對象。</p> + +<p>讓我們詳細了解 <strong>app.js</strong> 文件。首先,我們使用 <code>require()</code>將一些有用的 node 庫導入到文件中,其中包括我們先前使用 NPM 為應用程序下載的 express,serve-favicon,morgan,cookie-parser 和body-parser;和path 庫,它是解析文件和目錄路徑的核心 node 庫。</p> + +<pre class="brush: js notranslate">var express = require('express'); +var path = require('path'); +var favicon = require('serve-favicon'); +var logger = require('morgan'); +var cookieParser = require('cookie-parser'); +var bodyParser = require('body-parser'); +</pre> + +<p>然後我們用 <code>require()</code>導入來自我們的路由目錄的模塊。這些模塊/文件包含用於處理特定的相關“路由”集合(URL路徑)的代碼。當我們擴展骨架應用程序,例如列出圖書館中的所有書籍時,我們將添加一個新文件,來處理與書籍相關的路由。</p> + +<pre class="brush: js notranslate">var indexRouter = require('./routes/index'); +var usersRouter = require('./routes/users'); +</pre> + +<div class="note"> +<p><strong>注意:</strong> 此時我們剛剛導入了模塊;我們還沒有真正使用過它的路由(在文件的更下方一點將使用到路由)。</p> +</div> + +<p>接下來,我們使用導入的 express 模塊,創建應用程序 <code>app</code> 對象,然後使用它來設置視圖(模板)引擎。引擎的設置有兩個部分。首先我們設置 '<code>views</code>' 值,來指定模板將被存儲的文件夾(在這種情況下是子文件夾<strong> /views</strong>)。然後我們設置 '<code>view engine</code>' 的值,來指定模板庫(在本例中為 “pug” )。</p> + +<pre class="brush: js notranslate">var app = express(); + +// view engine setup +app.set('views', path.join(__dirname, 'views')); +app.set('view engine', 'pug'); +</pre> + +<p>下一組函數調用 <code>app.use()</code>,將中間件的庫,添加到請求處理鏈中。除了我們之前導入的第三方庫之外,我們還使用 <code>express.static</code> 中間件,來使 Express 提供在項目根目錄下,<strong>/public</strong> 目錄中的所有靜態文件。</p> + +<pre class="brush: js notranslate">// uncomment after placing your favicon in /public +//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); +app.use(logger('dev')); +app.use(bodyParser.json()); +app.use(bodyParser.urlencoded({ extended: false })); +app.use(cookieParser()); +<strong>app.use(express.static(path.join(__dirname, 'public')));</strong> +</pre> + +<p>現在所有其他中間件都已設置完畢,我們將(先前導入的)路由處理代碼,添加到請求處理鏈中。導入的代碼,將為網站的不同部分定義特定路由:</p> + +<pre class="brush: js notranslate">app.use('/', indexRouter); +app.use('/users', usersRouter); +</pre> + +<div class="note"> +<p><strong>注意:</strong> 上面指定的路徑 ('/' and '<code>/users</code>'),被視為定義在導入文件中的路由前綴。因此,例如,如果導入的用戶模塊 <strong>users</strong>為<code>/profile</code>定義了路由,則可以在 <code>/users/profile</code>中訪問該路由。我們將在後面的文章中,詳細討論路由。</p> +</div> + +<p>文件中的最後一個中間件,為錯誤和 HTTP 404 響應添加了處理程序方法。</p> + +<pre class="brush: js notranslate">// catch 404 and forward to error handler +app.use(function(req, res, next) { + var err = new Error('Not Found'); + err.status = 404; + next(err); +}); + +// error handler +app.use(function(err, req, res, next) { + // set locals, only providing error in development + res.locals.message = err.message; + res.locals.error = req.app.get('env') === 'development' ? err : {}; + + // render the error page + res.status(err.status || 500); + res.render('error'); +}); +</pre> + +<p>Express 應用程序對象(app)現已完全完成配置。最後一步,是將其添加到模塊導出(這允許它通過 <strong>/bin/www</strong> 導入)。</p> + +<pre class="brush: js notranslate">module.exports = app;</pre> + +<h3 id="路由">路由</h3> + +<p>路由文檔 <strong>/routes/users.js</strong> 如下所示(路由文件共享一個類似的結構,所以我們不需要也顯示 <strong>index.js</strong>)。首先加載 express 模塊,並使用它獲取<code> express.Router</code>對象。然後它在該對像上指定一個路由,最後從模塊中導出路由器(這就是允許將文件導入到 <strong>app.js</strong> 中的路由)。</p> + +<pre class="brush: js notranslate">var express = require('express'); +var router = express.Router(); + +/* GET users listing. */ +<strong>router.get('/', function(req, res, next) { + res.send('respond with a resource'); +});</strong> + +module.exports = router; +</pre> + +<p>該路由定義了一個回調,只要檢測到具有正確模式的HTTP <code>GET</code> 請求,就會調用該回調。匹配模式是模塊導入時指定的路由('<code>/users</code>'),加上('<code>/</code>')文件中定義的任何內容。換句話說,當收到<code>/users/</code>的 URL 時,將使用此路由。</p> + +<div class="note"> +<p><strong>提示:</strong> 嘗試運行帶有 node 的服務器,並在瀏覽器中訪問以下 URL: <a href="http://localhost:3000/users/">http://localhost:3000/users/</a>。您應該看到一條消息:'respond with a resource'。</p> +</div> + +<p>上面有趣的事情是,回調函數有第三個參數 '<code>next</code>',因此是一個中間件函數,而不是簡單的路由回調。雖然代碼當前不使用 <code>next</code> 參數,但如果要在'<code>/</code>'根路由路徑中,添加多個路由處理程序,將來可能會有用。</p> + +<h3 id="視圖模板">視圖(模板)</h3> + +<p>視圖(模板)存儲在 <strong>/views</strong> 目錄中(如<strong> app.js</strong> 中指定的)並且被賦予文件擴展名<strong>.pug</strong>。方法 <code><a href="http://expressjs.com/en/4x/api.html#res.render">Response.render()</a></code>用於呈現指定的模板,以及在對像中傳遞的命名變量的值,然後將結果作為響應發送。在來自<strong> /routes/index.js </strong>的以下代碼中,您可以看到,該路由如何使用模板 "index" 傳遞模板變量 "title" ,以呈現響應。</p> + +<pre class="brush: js notranslate">/* GET home page. */ +router.get('/', function(req, res) { + res.render('index', { title: 'Express' }); +}); +</pre> + +<p>上面路由的相應模板在下面給出(<strong>index.pug</strong>)。我們稍後會詳細討論這個語法。您現在需要知道的是,標題變量 <code>title</code>(值為 '<code>Express</code>')將插入模板中指定的位置。</p> + +<pre class="notranslate">extends layout + +block content + h1= title + p Welcome to #{title} +</pre> + +<h2 id="挑戰自己">挑戰自己</h2> + +<p>在 <strong>/routes/users.js </strong>中創建一個新路由,它將在 <code>/users/cool/</code>上顯示文本 “You're so cool”。通過運行服務器,並在瀏覽器中訪問 <a href="http://localhost:3000/users/cool/">http://localhost:3000/users/cool/</a> 來測試它。</p> + +<ul> +</ul> + +<h2 id="總結">總結</h2> + +<p>你現在為 本地圖書館 創建了一個骨架網站項目,並且用 node 驗證了它能夠運行。最重要的,你也理解了項目的結構,因此你也明白了我們需要為本地圖書館加上路由和視圖。</p> + +<p>接下來我們將開始修改骨架,讓它能像一個圖書館網站一樣運作。</p> + +<h2 id="參閱">參閱</h2> + +<ul> + <li><a href="https://expressjs.com/en/starter/generator.html">Express application generator</a> (Express docs)</li> + <li><a href="https://expressjs.com/en/guide/using-template-engines.html">Using template engines with Express</a> (Express docs)</li> +</ul> + +<p>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/Tutorial_local_library_website", "Learn/Server-side/Express_Nodejs/mongoose", "Learn/Server-side/Express_Nodejs")}}</p> + + + +<h2 id="本教程連結">本教程連結</h2> + +<ul> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node introduction</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">Setting up a Node (Express) development environment</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Express Tutorial: The Local Library website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Express Tutorial Part 2: Creating a skeleton website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Express Tutorial Part 3: Using a Database (with Mongoose)</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/routes">Express Tutorial Part 4: Routes and controllers</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/deployment">Express Tutorial Part 7: Deploying to production</a></li> +</ul> diff --git a/files/zh-tw/learn/server-side/express_nodejs/tutorial_local_library_website/index.html b/files/zh-tw/learn/server-side/express_nodejs/tutorial_local_library_website/index.html new file mode 100644 index 0000000000..6804ef3742 --- /dev/null +++ b/files/zh-tw/learn/server-side/express_nodejs/tutorial_local_library_website/index.html @@ -0,0 +1,91 @@ +--- +title: 'Express 教學 1: 本地圖書館網站' +slug: Learn/Server-side/Express_Nodejs/Tutorial_local_library_website +translation_of: Learn/Server-side/Express_Nodejs/Tutorial_local_library_website +--- +<div>{{LearnSidebar}}</div> + +<div>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/development_environment", "Learn/Server-side/Express_Nodejs/skeleton_website", "Learn/Server-side/Express_Nodejs")}}</div> + +<p class="summary">我們實作教程系列的第一篇文章,會說明將學到什麼東西,並提供「本地圖書館」範例網站的概述 。我們將在接下來的文章中一步一步完成這個網站。</p> + +<table class="learn-box standard-table"> + <tbody> + <tr> + <th scope="row">前置條件:</th> + <td>閱讀 <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Express 介紹。</a> 在底下的教程,你將需要 <a href="/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">架設一個 Node 開發環境。</a></td> + </tr> + <tr> + <th scope="row">目標:</th> + <td>介紹本教程的範例應用,讓讀者理解包含哪些主題。</td> + </tr> + </tbody> +</table> + +<h2 id="概覽">概覽</h2> + +<p>歡迎來到 MDN "本地圖書館" Express (Node) 教程,我們將開發一個網站,用於管理本地圖書館的目錄。</p> + +<p>本系列教程文章中,你將會:</p> + +<ul> + <li>使用 <em>Express 應用產生器工具,創建一個骨架網站與應用</em></li> + <li>起動和停止Node 網頁伺服器</li> + <li>使用數据庫存放應用的數据</li> + <li>創建路由用以要求不同的信息,創建模板 ("視圖") 以HTML的形式在瀏覽器中呈現數据</li> + <li>使用表單</li> + <li>部署應用到生產環境</li> +</ul> + +<p>這些主題中,有一部分你可能已經學過了,或者曾經簡短的接觸過。在本列系教程的最後,你應該知道的夠多,能夠自己開發簡單的 Express 應用。</p> + +<h2 id="本地圖書館網站">本地圖書館網站</h2> + +<p><em>我們接下來將創建,並隨著本系列教程發展的網站,名字是本地圖書館。如同你的預測,此網站的目的,是為一間小型本地圖書館,提供一個線上目錄,使用者能夠瀏覽可取得的書本</em>,並管理他們的帳号。</p> + +<p>本範例經過細心地考慮,因為它的規模可以放大或縮小,以配合我們的需要,演示盡可能多或少的細節。並且可以用來演示幾乎所有的 Express 特性。更重要的,它允許我們提供一條引導路徑,演示你在任何網站都會需要的功能:</p> + +<ul> + <li>在教程一開始,我們將定義一個簡單的、只能瀏覽的圖書館,圖書館成員能夠用來找到可以借的書。這允許我們找出,幾乎每個網站都會使用的共同操作: 從數据庫讀取並呈現內容。</li> + <li>跟隨教程的進展,圖書館的例子會一步一步擴充,以演示更高級的網站特征。比如我們會擴充圖書館,允許新書能夠被創建,並用這個來演示如何使用表單,並支持使用者授權。</li> +</ul> + +<p>即使這是一個具備相當擴充性的範例,它被叫做<strong>本地</strong>圖書館是有原因的 — 我們希望呈現給你最少的信息,能夠盡快幫助你上手並運行Express。因此,我們將會存放書本、複本、作者、和其它關鍵信息。然而,我們不會存放其它圖書館可能用到的有關信息,或者提供支持多個圖書館網站的架構,又或者其它 "大型圖書館" 的特性。</p> + +<h2 id="我被卡住了,哪裡可以得到原始碼">我被卡住了,哪裡可以得到原始碼?</h2> + +<p>當你使用本教程,我們將在每個知識點,提供適當的代碼片段,讓你複制貼上,同時有些代碼,我們希望你能自己擴充 (會有一些指引)。</p> + +<p>如果你被卡住了,你可以在 <a class="external external-icon" href="https://github.com/mdn/express-locallibrary-tutorial" rel="noopener">Github 的這裡</a>,找到本地圖書館網站已經開發完成的版本。</p> + +<div class="note"> +<p><strong>注意:</strong> 在本教程中,指定版本的 node、Express、還有其它模組,都經過測試,並列出在專案項目的 <a class="external external-icon" href="https://github.com/mdn/express-locallibrary-tutorial/blob/master/package.json" rel="noopener">package.json</a> 檔案中。</p> +</div> + +<h2 id="總結Edit">總結<a class="button section-edit only-icon" href="https://developer.mozilla.org/zh-CN/docs/learn/Server-side/Express_Nodejs/Tutorial_local_library_website$edit#總結" rel="nofollow, noindex"><span>Edit</span></a></h2> + +<p>現在,你對本地圖書館網站以及將要學習的東西,有更多一點的認識,是時候開始創建一個 <a href="https://developer.mozilla.org/zh-TW/docs/Learn/Server-side/Express_Nodejs/skeleton_website">骨架項目</a>,以存放我們的範例。</p> + +<p> </p> + +<p>{{PreviousMenuNext("Learn/Server-side/Express_Nodejs/development_environment", "Learn/Server-side/Express_Nodejs/skeleton_website", "Learn/Server-side/Express_Nodejs")}}</p> + +<p> </p> + +<p> </p> + +<h2 id="本系列教學">本系列教學</h2> + +<ul> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Introduction">Express/Node introduction</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">Setting up a Node (Express) development environment</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Tutorial_local_library_website">Express Tutorial: The Local Library website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/skeleton_website">Express Tutorial Part 2: Creating a skeleton website</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/mongoose">Express Tutorial Part 3: Using a Database (with Mongoose)</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/routes">Express Tutorial Part 4: Routes and controllers</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/Displaying_data">Express Tutorial Part 5: Displaying library data</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/forms">Express Tutorial Part 6: Working with forms</a></li> + <li><a href="/en-US/docs/Learn/Server-side/Express_Nodejs/deployment">Express Tutorial Part 7: Deploying to production</a></li> +</ul> + +<p> </p> |