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 [课程]


<<:  #20 No-code 之旅 — Analytics ft. Google Analytics & Splitbee

>>:  每日挑战,从Javascript面试题目了解一些你可能忽略的概念 - Day20

[DAY 19] 验算得分的理由及注意事项

上一次讲完了回应试算表 接下来要说说验算得分的部分 为什麽要验算得分 你可能会问 将google f...

Flutter体验 Day 23-WebSocket

WebSocket 前端对於WebSocket这项技术应该不陌生,以往会需要使用轮询的方式更新资料,...

Day28 火堆实作 - 模组参数

昨天我们提到把模组都连起来,接着我们就可以调整模组上的参数了, 首先看到 " Mappin...

[Day14]What is Hash? part.2

今天是第二天介绍hash! 总结一下hash,其实有两个很重要的重点: 不能让任何人从hash导出...

样本指纹与模型库中的模板匹配(The sample fingerprint matches the template in the model repository)

-零假设和替代假设(来源:PrepNuggets) 原假设和替代假设(Null and Alter...