Slide 1

Slide 1 text

Fast Web Development with Express 陳嘉輝 @tommy351 1

Slide 2

Slide 2 text

安裝 npm install express --save 2

Slide 3

Slide 3 text

Hello World var express = require('express'); var app = express(); app.get('/', function(req, res){ res.send('Hello world'); }); app.listen(4000, function(){ console.log('Server started!'); }); 3

Slide 4

Slide 4 text

4 ⽅方法 app.VERB('/users/:id', function(req, res, next){}); use:Middleware get:取得資料 post:建⽴立資料 put:取代資料 patch:更新資料 delete:刪除資料

Slide 5

Slide 5 text

5 路徑 app.VERB('/users/:id', function(req, res, next){}); :id:冒號開頭視為參數 :id?:結尾加上 ”?” 代表選填參數

Slide 6

Slide 6 text

6 Handler app.VERB('/users/:id', function(req, res, next){}); req:請求 res:回應 next:進⼊入下⼀一個 Handler

Slide 7

Slide 7 text

Middleware • 所有路徑符合的函數都會依序執⾏行 • 直到 next 函數被呼叫之前,下⼀一個函數不會被執⾏行 • 如果 next 函數帶有參數時,則會跳出錯誤 7

Slide 8

Slide 8 text

8 / /users/:id /users/:id http://localhost:4000/ 回應 x x 404 Not Found

Slide 9

Slide 9 text

9 / /users/:id http://localhost:4000/users/tommy x 回應 /users/:id 䎛↡袂⹤㽳竑完⫘嬭獑 404 Not Found

Slide 10

Slide 10 text

10 / /users/:id /users/:id next() http://localhost:4000/users/tommy 回應 x ㊦櫩❝⛌PGZV  㔮㧤蒢⑆⃬⃡⋬JCPFNGT 404 Not Found

Slide 11

Slide 11 text

EJS app.set('views', __dirname + '/views'); app.set('view engine', 'html'); app.engine('html', require('ejs').renderFile); • EJS 是⼀一種 JavaScript 模版引擎 • 安裝:npm install ejs --save 11

Slide 12

Slide 12 text

模版 app.get('/users/:id', function(req, res, next){ res.render('users/show', {user: req.user}); }); 12 My name is <%= user.name %> and I am <%= user.age %> years old. My name is Jack and I am 25 years old.

Slide 13

Slide 13 text

模版 - 陣列 13 My name is <%= user.name %> and I am <%= user.age %> years old. Here's my wishlist:
    <% user.wishlist.forEach(function(item){ %>
  • <%= item %>
  • <% }) %>
My name is Jack and I am 25 years old. Here's my wish list: • iPhone 6 • Car

Slide 14

Slide 14 text

Query string 14 http://localhost:4000/users/1?a=b&c=d • ? 後⾯面的字串即為 Query string • 每個參數以 & 分隔 • key 和 value 以 = 分隔 • 在 Express 中使⽤用 req.query 讀取 Query string app.get('/', function(req, res){ console.log(req.query); });

Slide 15

Slide 15 text

Body • Body 是 HTTP 請求的內容 • 使⽤用 body-parser 解析表單內容:npm install body-parser --save 15 app.use(require('body-parser').urlencoded({ extended: true }));

Slide 16

Slide 16 text

實作 留⾔言板 16

Slide 17

Slide 17 text

Thanks 17