[Express.js]取得網頁參數的三種方法

LingNi-Lee
Ling-Ni Lee
Published in
4 min readNov 1, 2019

前個練習使用到Express框架中params及query方法來取的網頁參數,查了一下文章發現還有req.body方法可以用,這邊整理一下三種方法以便查詢

2018.03.10 冰島 雷克雅維克 Hallgrimskirkjar教堂

・req.params

當參數存在 URL 網址中時,使用 req.params 來獲取參數

當前使用的伺服器網址為 http://localhost:300

當連到http://localhost/:here 網址時,:here為動態路由,會根據動態路由所產生不同的網址而回傳不同的資料

console.log(req) 會回傳整筆資料

console.log(req.params)會回傳包含動態路由的object

console.log(req.params.here)則會回傳 :here 在網址上所取得的值(String)

・req.query

當參數存在 URL 網址中時,使用 req.query 來獲取參數

此處的網址預設為http://localhost/3000/search?keyword=searchinput

用來取得網頁搜尋欄輸入的資料,搜尋資料的回傳由form表單取得

input tag中的 name=”keyword”則會顯示在網址上

http://localhost/3000/search?keyword=searchinput

searchinput則為input表單輸入的值

google範例

google輸入app的搜尋範例

・req.body

req.body用來取的POST表單送出的資料,使用上需再安裝一個middleware 「body-parser

app.use(bodyParser.urlencoded({ extended: true }));

載入body-parser module後,需設定從POST表單或取的URL加密資料,將它展開為object資料型態,方便使用。

表單中的資料取得:

  1. 使用<input type=”checkbox” name=”test”>,後端取得方式:req.body,name則為req.body的key資料,若勾選則顯示”on”,無勾選則不存在此資料

Example:若網頁存在三個checkbox表單

<form>
<input type=”text” name=”word”> 文字
<input type=”checkbox” name=”test1”> v(勾選)
<input type=”checkbox” name=”test2”> v(勾選)
<input type=”checkbox” name=”test3”>
</form>

使用body-parser取得資料

req.body{
word:'文字',
test1:"on",
test2:"on"
}

2.使用<input type=”radio” name=”group” value=”test1”>,後端取得方式:req.body,value則為req.body的key資料,若勾選則顯示”on”,無勾選則不存在此資料,radio選單中,若name相同,在同一group只可勾選1個check。

Example:若網頁存在三個radio表單

<form>
<input type=”radio” name=”group” value="test1"> v(勾選)
<input type=”radio” name=”group” value="test1">
<input type=”radio” name=”group” value="test1">
</form>

使用req.body取得資料,

req.body{
group:"test1"
}

以上為一些整理,方便自己記憶

也在忘記如何取的參數時可以更快速複習

--

--