Web開發學習筆記21 — RESTful Routes


Posted by Teagan Hsu on 2021-01-15

配合 The Web Developer Bootcamp 2021 Section 35: Defining RESTful Routes

Get與Post的差異

  • Get

    • 通常用來檢索資料
    • Data透過query string傳送
    • 資訊在url可見
    • 有限制傳送的資料的長度
  • Post

  • 通常用來發送資料給伺服器
  • 用來「寫」、「創造」、「更新」、「刪除」
  • Data透過request body傳送
  • 可以傳送任何的data類型(例如:Json)

req.body

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser and multer. - express

預設值是undefined,所以要用body-parsermulter進行填充(populate):

const bodyParser = require('body-parser')
app.use(bodyParser.json())  //for parsing application/json
app.use(bodyParser.urlencoded({ extended: true }))  // for parsing application/x-www-form-urlencoded

app.post('/form', (req, res) => {
    const { meat, qty } = req.body
    res.send(`You order ${qty} ${meat}!`)
})

什麼是REST?

Rest(Representational State Transfer)翻譯又叫做表現層狀態轉換,是一種全球資訊網軟體架構的風格(並非標準)。像是HTTP就可以視為Rest的實作,但不是所有HTTP都是Rest風格。

什麼是RESTful?

RESTful就是符合REST風格的路由設計,舉例來說RESTful的CRUD(Create、Delete、Read、Update)路由會這樣寫:

  • 檢索資料: GET http://.../form
  • 檢索特定資料:GET http://.../form/:id
  • 新增特定資料:POS http://.../form
  • 修改特定資料:PUT http://.../form/:id
  • 刪除特定資料:DELETE http://.../form/:id

特定的操作對應不同的HTTP Method以及url

RESTful Comment

  • index
    • get /comments
  • new
    • get /comments/new (給一個新表格)
    • post /comments (post data)
  • show
    • get /comments/:id (顯示特定id的留言)
  • edit
    • get /comments/:id/edit (給一個特定id編輯用表格)
    • patch /comments/:id (update data)
  • delete
    • delete /comments/:id (刪除特定留言)

method-override

安裝method-override

npm i method-override

override using a query value

HTML裡的form的method只有post和get,當我們想用例如:delete、patch、put...等時,就可以用express的override來解決:

//app.js
const express = require('express')
const methodOverride = require('method-override')
const app = express()

app.use(methodOverride('_method')) //記得底線

//index.ejs
<form method="POST" action="/comments?_method=DELETE"> //後面接?_method=[request method]
....
</form>

用id選取特定comment

app.get('/comments/:id', (req, res) => {
const {id} = req.params; //把req.params存成變數id
const comment = comments.find(c => c.id === id) //用array.find()找到符合對應id的留言,並存成變數comment
res.render('show', { comment }) //傳參數給render的頁面
})

新建comment

app.post('comments', (req, res) => {
const { username, comment } = req.body //取req.body的值,並存成變數
comments.push({ username, comment, id: uuid() }) //給新的username加上id,並且把這些值push到陣列中
res.redirect('/comments') //重新導向/comments
})

編輯comment

app.patch('/comments/:id/edit', (req, res) => {
const {id} = req.params; //把req.params存成變數id
const comment = comments.find(c => c.id === id) //用array.find()找到符合對應id的留言,並存成變數comment
const commentText = req.body.comment //取req.body裡的comment並存成commentText
comment.comment = commentText 特定id物件裡的留言內容 = 新改的留言內容
res.redirect('/comments')
})

刪除comment

app.delete('/comments/:id', (req, res) => {
const {id} = req.params; //把req.params存成變數id
const comments = comments.filter(c => c.id !== id) //用array.filter過濾出剩下的留言,並把原本的comments陣列 = filter的結果
res.redirect('/comments')
})

參考資料:

  1. 什麼是REST? 認識 RESTful API 路由語義化設計風格
  2. 筆記 REST 到底是什麼
  3. Express method-override middleware

#RESTful #REST







Related Posts

# JavaScript Immutable ( 不可變 ) 概念

# JavaScript Immutable ( 不可變 ) 概念

User Persona Analysis - H&M

User Persona Analysis - H&M

CSS3 Flex 的重要觀念

CSS3 Flex 的重要觀念


Comments