Express Tutorial Part 2: Creating a skeleton website

2018-05-15 17:26 更新
先決條件: 設(shè)置節(jié)點開發(fā)環(huán)境。 查看快速教程。
目的: 要使用快速應(yīng)用程序生成器啟動您自己的新網(wǎng)站項目。

概述

本文介紹如何使用 Express應(yīng)用生成器工具創(chuàng)建"骨架"網(wǎng)站, 然后您可以填充站點特定的路由,視圖/模板和數(shù)據(jù)庫調(diào)用。 在這種情況下,我們將使用該工具為我們的本地圖書館網(wǎng)站創(chuàng)建框架,我們稍后會將所需的所有其他代碼添加到 現(xiàn)場。 該過程非常簡單,只需要在命令行上使用新的項目名稱調(diào)用生成器,也可以指定網(wǎng)站的模板引擎和CSS生成器。

以下部分顯示如何調(diào)用應(yīng)用程序生成器,并提供有關(guān)不同視圖/ CSS選項的一些說明。 我們還將解釋骨架網(wǎng)站的結(jié)構(gòu)。 最后,我們將展示如何運行網(wǎng)站以驗證其是否有效。

注意:Express應(yīng)用程序生成器不是Express應(yīng)用程序的唯一生成器,生成的項目不是唯一的 可行的方式來構(gòu)造您的文件和目錄。 然而,生成的站點具有容易擴展和理解的模塊化結(jié)構(gòu)。 有關(guān)最低 Express應(yīng)用程序的信息,請參閱 Hello world示例 a>(Express docs)。

使用應(yīng)用程序生成器

您應(yīng)該已經(jīng)將生成器作為設(shè)置Node開發(fā)環(huán)境的一部分安裝。 作為一個快速提醒,您可以使用NPM軟件包管理器在站點范圍內(nèi)安裝生成器工具,如圖所示:

npm install express-generator -g

生成器有很多選項,您可以使用 - help (或 -h )命令在命令行中查看這些選項:

> 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

您可以使用 Jade 視圖引擎和純CSS( 目錄中簡單指定 express 該項目將在具有該名稱的子文件夾中創(chuàng)建)。

express

您還可以使用 - view 和/或使用 - css 的CSS生成引擎選擇視圖(模板)引擎。

注意:選擇模板引擎的其他選項(例如 - hgan , - ejs , - hbs 等等)已被棄用。 使用 - view (或 -v )!

我應(yīng)該使用什么視圖引擎?

Express應(yīng)用程序生成器 允許您配置一些流行的視圖/模板引擎,包括 EJS , Hbs , .org / api / getting-started.html"> Pug (Jade), Twig >和 Vash ,但如果您未指定視圖選項,則默認選擇Jade。 Express本身也可以支持大量其他模板語言開箱即用

注意:如果您要使用生成器不支持的模板引擎,請參閱 -template-engines.html">使用帶有Express的模板引擎(Express docs)和目標視圖引擎的文檔。

一般來說,你應(yīng)該選擇一個模板引擎,提供你需要的所有功能,并允許你更快的生產(chǎn)效率,換句話說,就像你選擇任何其他組件一樣! 比較模板引擎時需要考慮的一些事情:

  • Time to productivity — If your team already has experience with a templating language then it is likely they will be productive faster using that language. If not, then you should consider the relative learning curve for candidate templating engines.
  • Popularity and activity — Review the populartity of the engine and whether it has an active community. It is important to be able to get support for the engine when you have problems over the lifetime of the website.
  • Style — Some template engines use specific markup to indicate inserted content within "ordinary" HTML, while others construct the HTML using a different syntax (for example, using indentation and block names).
  • Performance/rendering time.
  • Features — you should consider whether the engines you look at have the following features available:
    • Layout inheritence: Allows you to define a base template and then "inherit" just the parts of it that you want to be different for a particular page. This is typically a better approach than building templates by including a number of required components, or building a template from scratch each time.
    • "Include" support: Allows you to build up templates by including other templates.
    • Concise variable and loop control syntax.
    • Ability to filter variable values at template level (e.g. making variables upper-case, or formatting a date value).
    • Ability to generate output formats other than HTML (e.g. JSON or XML).
    • Support for asynchronous operations and streaming.
    • Can be used on the client as well as the server. If a templating engine can be used on the client this allows the possibility of serving data and having all or most of the rendering done client-side.

提示:Internet上有許多資源可幫助您比較不同的選項!

對于此項目,我們將使用 Pug 模板引擎(這是最近更名的Jade 引擎),因為這是最流行的Express / JavaScript模板語言之一,并且由生成器支持開箱即用。

我應(yīng)該使用什么CSS樣式表引擎?

Express應(yīng)用程序生成器 允許您創(chuàng)建配置為使用最常見的CSS樣式表引擎的項目: LESS , SASS .org /">指南針, Stylus

注意: CSS有一些限制,使某些任務(wù)變得困難。 CSS樣式表引擎允許您使用更強大的語法來定義CSS,然后將定義編譯為普通CSS以供瀏覽器使用。

與模板引擎一樣,您應(yīng)該使用樣式表引擎,使您的團隊最有效率。 對于這個項目,我們將使用普通CSS(默認),因為我們的CSS需求不夠復(fù)雜,不能使用任何其他東西。

我應(yīng)該使用什么數(shù)據(jù)庫?

生成的代碼不使用/包括任何數(shù)據(jù)庫。 應(yīng)用程式可以使用任何資料庫機制, em> Node ( 本身并沒有定義數(shù)據(jù)庫管理的任何特定附加行為/要求)。

我們將在后面的文章中討論如何與數(shù)據(jù)庫集成。

創(chuàng)建項目

對于我們要創(chuàng)建的示例本地庫應(yīng)用程序,我們將使用 Pug 模板創(chuàng)建一個名為 express-locallibrary-tutorial 的項目 庫和沒有CSS樣式表引擎。

首先導(dǎo)航到您要創(chuàng)建項目的位置,然后在命令提示符下運行 Express Application Generator ,如下所示:

express express-locallibrary-tutorial --view=pug

生成器將創(chuàng)建(并列出)項目的文件。

   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

在輸出結(jié)束時,生成器提供有關(guān)如何安裝依賴關(guān)系(如 package.json 文件中所列)以及如何運行應(yīng)用程序的說明(以上說明適用于Windows;在Linux上 / Mac OS X,他們會略有不同)。

運行骨架網(wǎng)站

在這一點上,我們有一個完整的骨架項目。 網(wǎng)站實際上并不實際,但是值得運行它來顯示它的工作原理。

  1. First install the dependencies (the install command will fetch all the dependency packages listed in the project's package.json file).
    cd express-locallibrary-tutorial
    npm install
  2. Then run the application.
    • On Windows, use this command:
      SET DEBUG=express-locallibrary-tutorial:* & npm start
    • On Mac OS X or Linux, use this command:
      DEBUG=express-locallibrary-tutorial:* npm start
      
  3. Then load http://localhost:3000/ in your browser to access the app.

您應(yīng)該會看到如下所示的瀏覽器頁面:

您有一個工作中的Express應(yīng)用程序,本身服務(wù)于 localhost:3000 。

注意:您也可以使用 npm start 命令啟動應(yīng)用。 如圖所示指定DEBUG變量可啟用控制臺日志記錄/調(diào)試。 例如,當您訪問上述頁面時,您將看到如下所示的調(diào)試輸出:

>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

對文件更改啟用服務(wù)器重新啟動

您對Express網(wǎng)站所做的任何更改目前在重新啟動服務(wù)器之前都不可見。 每次進行更改時,都必須停止并重新啟動服務(wù)器,所以很有必要花時間在需要時自動重新啟動服務(wù)器。

用于此目的的最簡單的此類工具之一是 nodemon 。 這通常是安裝在全局(因為它是一個"工具"),但在這里我們將安裝和使用它作為一個開發(fā)人員依賴,所以任何開發(fā)人員工作時, 安裝應(yīng)用程序。 在骨干項目的根目錄中使用以下命令:

npm install --save-dev nodemon

如果您打開項目的 package.json 文件,您將看到一個包含此依賴關(guān)系的新部分:

  "devDependencies": {
    "nodemon": "^1.11.0"
  }

由于該工具未全局安裝,因此無法從命令行啟動(除非將其添加到路徑中),但是我們可以從NPM腳本調(diào)用它,因為NPM知道所有已安裝的軟件包。 將粗體顯示的線和逗號添加到package.json的scripts部分(注意逗號被添加到上一行!):

  "scripts": {
    "start": "node ./bin/www",
    "devstart": "nodemon ./bin/www"
  },

我們現(xiàn)在可以以與以前幾乎完全相同的方式啟動服務(wù)器,但是以下添加以粗體顯示如下:

SET DEBUG=express-locallibrary-tutorial:* & npm run devstart

現(xiàn)在如果編輯項目中的任何文件,服務(wù)器將重新啟動(或者您可以在任何時候在命令提示符下鍵入 rs 重新啟動它)。 您仍然需要重新加載瀏覽器以刷新頁面。

注意:我們現(xiàn)在必須調(diào)用" npm run < scriptname> ",而不是僅僅 npm start "start"實際上是映射到命名腳本的NPM命令。 我們可以替換啟動腳本中的命令,但我們只想在開發(fā)期間使用 nodemon ,因此創(chuàng)建一個新的腳本命令是有意義的。

生成的項目

讓我們來看看我們剛剛創(chuàng)建的項目。

目錄結(jié)構(gòu)

生成的項目,現(xiàn)在您已安裝依賴項,具有以下文件結(jié)構(gòu)(文件是前綴"/"的項目)。 package.json 文件定義應(yīng)用程序依賴性和其他信息。 它還定義了一個啟動腳本,它將調(diào)用應(yīng)用程序入口點,JavaScript文件 / bin / www 。 這會設(shè)置一些應(yīng)用程序錯誤處理,然后加載 app.js 以完成其余工作。 應(yīng)用程序路徑存儲在 routes / 目錄下的單獨模塊中。 模板存儲在/ 視圖目錄下。

/express-locallibrary-tutorial
    app.js
    /bin
?       www
    package.json
    /node_modules
?       [about 4,500 subdirectories and files]
    /public
?       /images
?       /javascripts
?       /stylesheets
?           style.css
    /routes
        index.js
?       users.js
    /views
?       error.pug
        index.pug
?       layout.pug
    

以下部分將更詳細地描述文件。

package.json

package.json 文件定義應(yīng)用程序依賴性和其他信息:

{
  "name": "express-locallibrary-tutorial",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www",
    "devstart": "nodemon ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.15.2",
    "cookie-parser": "~1.4.3",
    "debug": "~2.2.0",
    "express": "~4.14.0",
    "morgan": "~1.7.0",
    "pug": "~2.0.0-beta6",
    "serve-favicon": "~2.3.0"
  },
  "devDependencies": {
    "nodemon": "^1.11.0"
  }
}

相關(guān)性包括 express 包和我們所選視圖引擎( pug )的包。 此外,我們有以下包在許多Web應(yīng)用程序中有用:

  • body-parser: This parses the body portion of an incoming HTTP request and makes it easier to extract different parts of the contained information. For example, you can use this to read POST parameters.
  • cookie-parser: Used to parse the cookie header and populate req.cookies (essentially provides a convenient method for accessing cookie information).
  • debug: A tiny node debugging utility modelled after node core's debugging technique.
  • morgan: An HTTP request logger middleware for node.
  • serve-favicon: Node middleware for serving a favicon (this is the icon used to represent the site next inside the browser tab, bookmarks, etc.).

腳本部分定義了一個" start "腳本,這是我們在調(diào)用 npm start 啟動服務(wù)器時調(diào)用的腳本。 從腳本定義中,您可以看到,這實際上會使用節(jié)點啟動JavaScript文件 ./ bin / www 。 它還定義了一個" devstart "腳本,我們在調(diào)用 npm run devstart 時調(diào)用它。 這會啟動相同的 ./ bin / www 文件,但使用 nodemon 而不是節(jié)點

  "scripts": {
    "start": "node ./bin/www",
    "devstart": "nodemon ./bin/www"
  },

www文件

文件 / bin / www 是應(yīng)用程序入口點! 這樣做的第一件事是 require()在項目根目錄中的"真實"應(yīng)用程序入口點( app.js ),設(shè)置并返回 express() 應(yīng)用程序?qū)ο蟆?/p>

#!/usr/bin/env node

/**
 * Module dependencies.
 */

var app = require('../app');

注意: require()是一個全局節(jié)點函數(shù),用于將模塊導(dǎo)入到當前文件中。 在這里,我們使用相對路徑并省略可選(。 js )文件擴展名來指定 app.js 模塊。

此文件中的其余代碼將設(shè)置一個節(jié)點HTTP服務(wù)器,并將 app 設(shè)置為特定端口(在環(huán)境變量中定義,如果變量未定義,則為3000),并開始偵聽和報告 服務(wù)器錯誤和連接。 現(xiàn)在你不需要知道任何關(guān)于代碼(這個文件中的一切都是"樣板"),但隨時審查它,如果你有興趣。

app.js

此文件創(chuàng)建一個 express 應(yīng)用程序?qū)ο?按照慣例名為 app ),使用各種設(shè)置和中間件設(shè)置應(yīng)用程序,然后從模塊導(dǎo)出應(yīng)用程序。 下面的代碼僅顯示了創(chuàng)建和導(dǎo)出應(yīng)用程序?qū)ο蟮奈募糠?

var express = require('express');
var app = express();
...
module.exports = app;

回到上面的 www 入口點文件,這是導(dǎo)入此文件時提供給調(diào)用方的 module.exports 對象。

讓我們詳細了解 app.js 文件。 首先,我們使用 require()將一些有用的節(jié)點庫導(dǎo)入到文件中,包括 ,,serve-favicon 我們之前使用NPM為我們的應(yīng)用程序下載的 cookie-parser body-parser path 解析文件和目錄路徑。

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');

然后我們從我們的routes目錄下的 require()模塊。 這些模塊/文件包含用于處理相關(guān)"路由"(URL路徑)的特定集合的代碼。 當我們擴展框架應(yīng)用程序時,例如列出庫中的所有圖書,我們將添加一個新文件來處理與書相關(guān)的路線。

var index = require('./routes/index');
var users = require('./routes/users');

注意:此時,我們只需導(dǎo)入模塊; 我們還沒有實際使用它的路由(這發(fā)生只是一點點下文件)。

接下來,我們使用導(dǎo)入的 express 模塊創(chuàng)建 app 對象,然后使用它來設(shè)置視圖(模板)引擎。 設(shè)置發(fā)動機有兩個部分。 首先,我們設(shè)置" views "值來指定存儲模板的文件夾(在這種情況下是子文件夾 / views )。 然后我們設(shè)置\'視圖引擎\'值來指定模板庫(在這種情況下為"pug")。

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');

下一組函數(shù)調(diào)用 app.use()中間件庫添加到請求處理鏈中。 除了我們先前導(dǎo)入的第三方庫,我們使用 Express.static 中間件來獲取 Express 來提供目錄中的所有靜態(tài)文件 / public / strong>。

// 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());
app.use(express.static(path.join(__dirname, 'public')));

現(xiàn)在所有其他中間件都已設(shè)置好,我們將(先前導(dǎo)入的)路由處理代碼添加到請求處理鏈。 導(dǎo)入的代碼將定義網(wǎng)站的不同部分的特定路由:

app.use('/', index);
app.use('/users', users);

注意:上面指定的路徑(\'/\'和\' / users\')將被視為導(dǎo)入文件中定義的路由的前綴。 因此,例如,如果導(dǎo)入的用戶模塊為 / profile 定義了一個路由,您將在 / users / profile 訪問該路由。 我們將在后面的文章中更多地討論路由。

文件中的最后一個中間件為錯誤和HTTP 404響應(yīng)添加了處理程序方法。

// 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');
});

Express應(yīng)用程序?qū)ο?應(yīng)用程序)現(xiàn)已完全配置。 最后一步是將它添加到模塊導(dǎo)出(這是允許它通過 / bin / www 導(dǎo)入)。

module.exports = app;

路線

路線文件 /routes/users.js 如下所示(路線文件共享相似的結(jié)構(gòu),因此我們不需要也顯示 index.js )。 首先它加載 express 模塊,并使用它來獲取一個 express.Router 對象。 然后它在該對象上指定一個路由,最后從模塊中導(dǎo)出路由器(這是允許將文件導(dǎo)入 app.js )的路由器。

var express = require('express');
var router = express.Router();

/* GET users listing. */
router.get('/', function(req, res, next) {
? res.send('respond with a resource');
});

module.exports = router;

路由定義了一個回調(diào),只要檢測到具有正確模式的HTTP GET 請求,就會調(diào)用該回調(diào)。 匹配模式是在導(dǎo)入模塊時指定的路由(\' / users \')加上此文件中定義的任何內(nèi)容(\' / \')。 換句話說,當接收到 / users / 的URL時,將使用此路由。

提示:嘗試通過運行帶有節(jié)點的服務(wù)器并訪問瀏覽器中的網(wǎng)址: http: // localhost:3000 / users / 。 您應(yīng)該看到一條消息:"使用資源響應(yīng)"。

上面感興趣的一個事情是回調(diào)函數(shù)有第三個參數(shù)\' next \',因此是一個中間件函數(shù),而不是一個簡單的路由回調(diào)。 沒有明顯的原因,因為代碼不使用 next 參數(shù),并沒有它工作正常。

視圖(模板)

視圖(模板)存儲在 / views 目錄中(如 app.js 中所指定),文件擴展名為 .pug 。 方法 Response.render() 是 用于渲染指定的模板以及在對象中傳遞的命名變量的值,然后將結(jié)果作為響應(yīng)發(fā)送。 在下面的 /routes/index.js 代碼中,您可以看到該路由如何使用傳遞模板變量"title"的模板"index"呈現(xiàn)響應(yīng)。

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

下面給出了上述路線的相應(yīng)模板( index.pug )。 稍后我們將更多地討論語法。 所有你需要知道的是,標題變量(值為"Express")插入到模板中指定的位置。

extends layout

block content
  h1= title
  p Welcome to #{title}

挑戰(zhàn)自己

/routes/users.js 中創(chuàng)建一個新路線,將在網(wǎng)址 / users / cool / 上顯示文字" >。 通過運行服務(wù)器并訪問 http:// localhost:3000 / users / cool / ,測試它 瀏覽器

    概要

    您現(xiàn)在已為本地庫創(chuàng)建了一個骨架網(wǎng)站項目,并驗證其是否使用節(jié)點運行。 最重要的是,您也了解項目的結(jié)構(gòu),所以您有一個好主意,我們需要更改添加路線和視圖為我們的本地圖書館。

    接下來,我們將開始修改骨架,使其成為一個圖書館網(wǎng)站。

    也可以看看

    以上內(nèi)容是否對您有幫助:
    在線筆記
    App下載
    App下載

    掃描二維碼

    下載編程獅App

    公眾號
    微信公眾號

    編程獅公眾號