透过Post方法提出请求时,浏览器会将请求以不同的形式递送,请求的内容会纪录在Content并以ContentType把请求的内容格式纪录在Header,常用的方法有送出网页表单(submit form)请求及以JSON格式字串为内容的请求等,今天会就submit form和JSON格式的请求分别练习。
实作submit form
app.use()
方法加入Express中的urlencoded()
方法,用於解析请求的表单内容。app.use(express.urlencoded({extended: false}));
post()
方法请求的Path,在回呼函式中设定回传内容,由於urlencoded()
方法将表单内容解析,可於函式内直接存取表单参数。app.post("/person", (req, res)=>{
res.send("Thank you");
console.log(req.body.firstName);
console.log(req.body.lastName);
});
<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>
/person
提出Post请求。console.log()
印出来的表单参数内容。实作JSON Post
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>
use()
方法加入express.json()
方法至主程序。app.use(express.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);
});
<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>
<label>
标签并在终端机印出请求参数fullName。表单提交和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
上一次讲完了回应试算表 接下来要说说验算得分的部分 为什麽要验算得分 你可能会问 将google f...
WebSocket 前端对於WebSocket这项技术应该不陌生,以往会需要使用轮询的方式更新资料,...
昨天我们提到把模组都连起来,接着我们就可以调整模组上的参数了, 首先看到 " Mappin...
今天是第二天介绍hash! 总结一下hash,其实有两个很重要的重点: 不能让任何人从hash导出...
-零假设和替代假设(来源:PrepNuggets) 原假设和替代假设(Null and Alter...