iT邦幫忙

2021 iThome 鐵人賽

DAY 20
0
自我挑戰組

學習NodeJS的30天系列 第 20

Day20 NodeJS-Express V

Post Parameter

透過Post方法提出請求時,瀏覽器會將請求以不同的形式遞送,請求的內容會紀錄在Content並以ContentType把請求的內容格式紀錄在Header,常用的方法有送出網頁表單(submit form)請求及以JSON格式字串為內容的請求等,今天會就submit form和JSON格式的請求分別練習。

實作submit form

  1. 透過app.use()方法加入Express中的urlencoded()方法,用於解析請求的表單內容。
app.use(express.urlencoded({extended: false}));
  1. 定義一個透過post()方法請求的Path,在回呼函式中設定回傳內容,由於urlencoded()方法將表單內容解析,可於函式內直接存取表單參數。
app.post("/person", (req, res)=>{
  res.send("Thank you");
  console.log(req.body.firstName);
  console.log(req.body.lastName);
});
  1. 在index頁面加入表單物件<form>與參數輸入項<input>及submit按鈕,表單內容設定方法為Post、動作為Path(/person),參數輸入項以name作為參數名稱。
<html>
  <head>
    <link href="/assets/style.css" type="text/css" rel="stylesheet" />
  </head>
  <body>
    <h1>Hello</h1>
    <form method="POST" action="/person">
      First Name: <input type="text" id="firstName" name="firstName" /></br>
      Last Name: <input type="text" id="lastName" name="firstName" /></br>
      <input type="submit" />
    </form>
  </body>
</html>
  1. 以瀏覽器請求初始頁面index,輸入表單內容後按提交,會對/person提出Post請求。

https://ithelp.ithome.com.tw/upload/images/20211005/201399806bW3IhbalS.png

  1. Post請求回傳內容為指定字串,從終端機可以確認console.log()印出來的表單參數內容。

https://ithelp.ithome.com.tw/upload/images/20211005/20139980TXBNTfSTHB.png

實作JSON Post

  1. 在JSON的Post練習中,會在前端使用到jQuery套件,可以透過npm install安裝,以Express的use()方法給予node_modules新的Path,並在HTML頁面以相對路徑引用jQuery套件。
app.use("/sources", express.static(`${__dirname}/node_modules`));
<script src="/sources/jquery/dist/jquery.min.js"></script>
  1. JSON資料格式需透過Express中的json()方法解析,以use()方法加入express.json()方法至主程式。
app.use(express.json());
  1. 建立一個Path為personJson的Post方法,設定回應內容為JSON格式資料,並以console.log()印出請求內容,這裡的req.body是透過express.json()解析後的請求內容。
app.post("/personJson", (req, res)=>{
  res.setHeader('Content-Type', 'application/json');
  res.send(JSON.stringify({ a: "Thank you for the JSON data" }));
  console.log(req.body.fullName);
});
  1. 在前端頁面的<body>加入要參數輸入項,並透過jQuery的$.ajax()方法提出Post請求,請求成功時將回應內容顯示於<label>標籤內。
Full Name: 
<input type="text" id="fullName" />
<button id="btnSend">JSON送出</button>
<label id="labName"></label>

<script>
  $("#btnSend").on("click", ()=>{
    $.ajax({
      type: "POST",
      url: "/personJson",
      data: JSON.stringify({fullName: $("#fullName").val()}),
      contentType: "application/json",
      dataType: "json",
      success: (data) => {
        $("#labName").text(data.a);
      }
    });
  });
</script>
  1. 執行程式並輸入請求內容,點擊綁定按鈕後回應的資料會顯示在<label>標籤並在終端機印出請求參數fullName。

https://ithelp.ithome.com.tw/upload/images/20211005/201399806ZtrNUnWPh.png

https://ithelp.ithome.com.tw/upload/images/20211005/20139980F0fFp40xzW.png

小結

表單提交和JSON格式的Post請求,可以讓傳遞的資料類型更多樣,相較於Get最大的差異應該是傳再多的參數都不會導致URL欄位內容長度增加,但Get方便的地方也就在於可以透過URL簡單變更請求參數,因應不同的用途選擇不同的請求方法或許可以讓應用程式更加靈活。

參考資料

https://www.npmjs.com/package/body-parser#bodyparserurlencodedoptions

http://expressjs.com/en/resources/middleware/body-parser.html

https://stackoverflow.com/questions/5710358/how-to-access-post-form-fields

Learn and Understand NodeJS [課程]


上一篇
Day19 NodeJS-Express IV
下一篇
Day21 NodeJS-Express VI
系列文
學習NodeJS的30天30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言