Node.js 學習第二十二天
如果在看的過程中有任何錯誤歡迎寫 E-MAIL: pp840405@gmail.com 提醒我錯誤。
Postman - API 管理工具
管理 API 好用的工具 Postman ,請按照自己的作業系統版本去安裝。
請務必邊做邊看
Postman 介紹
Postman - 取得 get 資料、基礎操作
請先建立下面 app.js 檔案。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16var express = require('express');
var app = express();
var engine = require('ejs-locals');
app.engine('ejs',engine);
app.set('views','./views');
app.set('view engine','ejs');
//靜態檔路徑
app.use(express.static('public'));
app.get('/',function(req,res){
res.send('你進入到首頁');
console.log('有人造訪首頁')
});
//監聽 port
var port = process.env.PORT || 3000;
app.listen(port);在 postman 新增一個專案資料夾 nodetest
- 新增好啟動 app.js 把 http://127.0.0.1:3000/ 你的網址貼到 postman 的 GET 欄上面然後點擊 send 下面欄位就會取得你 JS 檔案送出的資料,在把這資料 Save 到 nodetest 資料夾,名稱可以更改。
第一行是啟動 app.js 檔案進入首頁後出現的 console ,第二行是 postman GET 後得到的 console 。
之後就可以使用 postman 去測試資料了。
body-parser - 取得表單資料
請先安裝 body-parser 它是可以把前端表單資料傳送到後端資料庫去,會把資料都放在 req.body
上面。1
npm install body-parser --save
接下來要測試如何取得表單資料。
先新增下面的 app.js 檔案資料
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26var express = require('express');
var app = express();
var engine = require('ejs-locals');
//取得 body-parser 套件
var bodyParser = require('body-parser')
app.engine('ejs',engine);
app.set('views','./views');
app.set('view engine','ejs');
app.use(express.static('public'));
// body 解析
//內容支援JSON格式
app.use(bodyParser.json());
//解析表單內容({物件設定})
app.use(bodyParser.urlencoded({extended:false}));
app.get('/',function(req,res){
res.send('你進入到首頁');
console.log('有人造訪首頁')
});
//新增搜尋頁 讀取search.ejs
app.get('/search',function(req,res){
res.render('search');
});
//監聽 port
var port = process.env.PORT || 3000;
app.listen(port);新增一個 search.ejs 檔案
1
2
3
4
5
6<!-- 移動到/searchList 用post方式 -->
<form action="/searchList" method="post">
<input type="text" name="searchText" value="">
<input type="text" name="searchName" value="">
<input type="submit" value="送出">
</form>完成後啟動 app.js 進入 127.0.0.1:3000/search 看是否有載入 search.ejs 。
HTML 有設定資料移動到 searchList 路由上,所以要在 app.js 檔案新增一個路由上去後並啟動到 127.0.0.1:3000/search 。
1
2
3
4//app,post是當使用者傳送資料到後端伺服器可以接收到資料
app.post('/searchList',function(req,res){
console.log(req.body)
});
- 若沒有寫轉址的話不會結束動作,請按照下面寫轉址程式碼。
1
2
3
4
5
6
7app.post('/searchList',function(req,res){
console.log(req.body);
//轉址 到search路由上
res.redirect('search');
//若是使用render,是把search.ejs檔案渲染到/searchList路由上面
//res.render('search');
});
使用 postman 傳送表單資訊
可以使用 postman 模擬傳送表單資訊。
- 把 GET 改成 POST 並貼上 http://127.0.0.1:3000//searchList
- 網址欄下方選到 Body 欄位並選擇 x-www-form-urlencoded 傳輸格式(表單傳後端用格式)
- 可以在 Key 跟 Value 輸入你想要測試的值
結語
學到前端要如何要用怎樣格式去傳資料到後端,有任何問題歡迎寫 MAIL: pp840405@gmail.com 一起共同討論。