Top Banner
Lesson 2 Express 簡簡 By BigQ
24

nodejs -『PVD+』團隊內部Lesson2

Oct 31, 2014

Download

Technology

Mark Ven

『PVD+』團隊實習生: 許鈺群「BigQ」製作
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: nodejs -『PVD+』團隊內部Lesson2

Lesson 2Express 簡介

By BigQ

Page 2: nodejs -『PVD+』團隊內部Lesson2

Install Express我們可以透過之前介紹的 npm 安裝 express在終端輸入 npm install –g express

–g 代表在全域下都安裝 express 套件

Page 3: nodejs -『PVD+』團隊內部Lesson2

Install Express一、終端機輸入 express my_app( 也可以用 / 改變安裝目錄 )

二、下載 app 所需套件 cd my_app 進入目錄npm install

新增專案

Page 4: nodejs -『PVD+』團隊內部Lesson2

Install Express

已經新增好一個 express 的專案了 !預設執行檔為 app.js

Page 5: nodejs -『PVD+』團隊內部Lesson2

Install Express輸入 node app.js 執行

Page 6: nodejs -『PVD+』團隊內部Lesson2

Express - Hello world如同 http 模組,我們先建立一個 Hello World 。

Page 7: nodejs -『PVD+』團隊內部Lesson2

Express - Hello world儲存成 helloworld.js 並用終端機執行即可。

我們發現與 http 建立 server 的方法大同小異。http 模組 express 模組

Page 8: nodejs -『PVD+』團隊內部Lesson2

Express - Hello world用終端機執行時會出現以下

因為新版的 express可以不用 creatsetver 這個 function

Page 9: nodejs -『PVD+』團隊內部Lesson2

Express – Get & Router我們建立 Hello World 時 :

app.get 可以帶入兩個參數,第一個是路徑名稱設定,第二個為回應函式 (call back function) ,回應函式裡面就如同之前的 createServer 方法,裡面我們提出 request , response 兩個物件可供使用。

Page 10: nodejs -『PVD+』團隊內部Lesson2

Express - Get & Router我們可以用這樣的方法管理各頁面。

Page 11: nodejs -『PVD+』團隊內部Lesson2

Express - Get & Router

請注意斜線部分當初路徑設定為 /PVT 與 /user/

Page 12: nodejs -『PVD+』團隊內部Lesson2

Express - Get & Router

我們加入一個可以讀取使用者 ID 或是數字的頁面

Page 13: nodejs -『PVD+』團隊內部Lesson2

Express - Get & Router

我們用 app.all 這個方法,自己先內定哪些使用者名稱是在內部定義內的,如果輸入的路徑符合定義名稱,就會被分配到對應的方法裡面。

Page 14: nodejs -『PVD+』團隊內部Lesson2

Express - Get & Router經過上面的判斷式如果你是已經定義的使用者就會往以下路徑走

Page 15: nodejs -『PVD+』團隊內部Lesson2

Express - Get & Router經過上面的判斷式如果你是已經定義的使用者就會往以下路徑走

Page 16: nodejs -『PVD+』團隊內部Lesson2

Express - Get & Router經過上面的判斷式如果你是已經定義的使用者就會往以下路徑走

Page 17: nodejs -『PVD+』團隊內部Lesson2

Express – Get

我們現在要做一個表單可以輸入資訊讓 server 端讀取資訊分別用 GET 與 POST 的方式

Page 18: nodejs -『PVD+』團隊內部Lesson2

Express – Get

做一個簡單的互動頁面,路徑設為 localhost:3000/send並且用“ GET” 的方法處理 form 。

Page 19: nodejs -『PVD+』團隊內部Lesson2

Express – Get在瀏覽器上看到的樣貌。

Page 20: nodejs -『PVD+』團隊內部Lesson2

Express – Get現在按下 singnup ,路徑會接到 /send 去處理,所以我們需要一個 server 端對應的方式。

我們要讓 singup 從 express 中讀出我們輸入的Username, Email, Age 等資訊,並讓他有對應的路徑與互動。

Page 21: nodejs -『PVD+』團隊內部Lesson2

Express – Get

由 req.query.name 把 name 的值取出來。

最後 req.send 把相對應的處理傳給client 。

if 是來判斷 client 是不是真的有傳值到 server

Page 22: nodejs -『PVD+』團隊內部Lesson2

Express – Post同 Signup 的做法一樣,做一個可以交換資訊的form 。

Page 23: nodejs -『PVD+』團隊內部Lesson2

Express – Post

我們要輸入的地方是用<input …>

form 的方法為 POST

Page 24: nodejs -『PVD+』團隊內部Lesson2

Express – Post

用 bodyParser() 讓 express 可以來解析 post 傳來的資料,再來就是在處理 request 和 response 的 function 裡用 req.body  這個例子是用 req.body.username簡單想就是把 GET 用的 query 改成 body 就是了。