iT邦幫忙

2

node.js - express #4

pyk 2017-04-27 12:20:4138435 瀏覽
  • 分享至 

  • xImage
  •  

上次作了一個經由 GET來傳送資料的小表單,
這次要來改成使用 POST 傳送資料。

先複習一下form的 GET / POST 兩個動作差別

GET 和 POST 同樣都能傳送值

  • GET 會把要傳送的值放在header上,會直接顯示在URL,因此不適合傳輸隱密的資料,
    同時 GET 會被Cache紀錄、且有長度限制
  • POST是把資料放在訊息主體內進行傳送,不會被Cache紀錄且對資料長度沒有限制,
    因此POST比GET更安全,所以較適合用來傳送隱密性較高的資料

第四個應用:簡單的表單 - POST

因為我很懶xD 所以直接延用了上一個form.html,
只要把method改成 POST 就可以了

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>form</title>
	<style>
		h2 { text-align: center; }
		div { width: 400px; margin: 10px auto; }
		label{ width: 100%; display: inline-block; }
		input, textarea{ width: 100%; display: inline-block; }
		#send{ margin: 40px auto 0 auto; display: block; width: 50px; }
	</style>
</head>
<body>
	<h2>意見欄</h2>
	<form id="comment" method="POST" action="http://127.0.0.1:8082/sendcomment">
		<div><label for="name">姓名:</label><input type="text" name="name" id="name"></div>
		<div><label for="email">信箱:</label><input type="text" name="email" id="email"></div>
		<div><label for="comment">意見:</label><textarea name="comment" id="comment" cols="30" rows="10"></textarea></div>
		<input id="send" type="submit" value="送出">
	</form>
</body>
</html>

再來是修改 server.js

 var express = require('express');
 var app = express();
 app.get('/', function(req, res) {
     res.sendfile('./views/index.html');
 });
 app.get('/about', function(req, res) {
     res.sendfile('./views/about.html');
 });
 app.get('/form', function(req, res) {
     res.sendfile('./views/form.html');
 });
 //POST 動作
 app.post('/sendcomment', function(req, res) {
 	console.log('name:' + req.body.name);
    console.log('email' + req.body.email);
    console.log('comment' + req.body.comment);
    res.send(req.body.name + '謝謝你的回覆');
 });
 app.get('*', function(req, res) {
     res.send('404 not found');
 });
 var server = app.listen(8082, function() {
     console.log('Listening on port 8082');
 });

原本的 app.get 因為method改成post所以要改成 app.post

因為method是POST,相較於GET動作下訊息會被包成query string,
POST的訊息則是會被包在message body內,所以底下也要改為 req.body.<參數>

但是這樣改完後,應該會出現 TypeError: Cannot read property 'name' undefined

還需要把 server.js 修改成下面

 var express = require('express');
 var bodyParser = require('body-parser');
 var urlencodedParser = bodyParser.urlencoded({ extended: false });
 var app = express();
 app.get('/', function(req, res) {
     res.sendfile('./views/index.html');
 });
 app.get('/about', function(req, res) {
     res.sendfile('./views/about.html');
 });
 app.get('/form', function(req, res) {
     res.sendfile('./views/form.html');
 });
 //POST 動作
 app.post('/sendcomment',urlencodedParser, function(req, res) {
 	console.log('name:' + req.body.name);
    console.log('email' + req.body.email);
    console.log('comment' + req.body.comment);
    res.send(req.body.name + '謝謝你的回覆');
 });
 app.get('*', function(req, res) {
     res.send('404 not found');
 });
 var server = app.listen(8082, function() {
     console.log('Listening on port 8082');
 });

加上了

 var bodyParser = require('body-parser');
 var urlencodedParser = bodyParser.urlencoded({ extended: false });

也把POST地方改成

 app.post('/sendcomment',urlencodedParser, function(req, res) ...

第一篇文章時有提到 body-parser 可以解析json、row、文本、URL-encoded格式的表單資料
如果method是POST時,代表資料會是urlencoded type,因此必須加上 body-parser 來 parse 資料
如果是json格式會有不一樣的寫法

//json
bodyParser.json()
//urlencoded
bodyParser.urlencoded({ extended: false })

這邊有GET和POST更詳細的解釋 -> 表單中的 GET 與 POST 有什麼差別


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言