Node.js 的 30 天學習日記--第十八天

Node.js 學習第十八天

發覺學習速度有點慢,看來花有點多的時間再玩上面,離三十天都過一半多了但看過學習進度發現有點慢,要加多點時間在學習上面了。

如果在看的過程中有任何錯誤歡迎寫 E-MAIL: pp840405@gmail.com 提醒我錯誤。


query 取得網址參數

query 是撈取網址參數的資料,那參數是哪些呢?就像 https://www.google.com.tw/search?q=HistoryMaker 拿這 GOOGLE 網址來講,search 這是路由 ? 問號代表後面都是參數, q 代表是你參數的名稱,等於就不用說了後面就是你要搜尋的資料,如果你設定條件是多筆的話就要再參數名前後中間加上 & 符號。
你在你的網址輸入 127.0.0.1:3000/tom?limit=hello 網頁就會顯示 tom向你說hello
如果要設定第二條件就再新增新的參數名並再網址這樣打 127.0.0.1:3000/tom?limit=hello&參數名=條件

1
2
3
4
5
6
7
8
var express = require('express');
var app = express();
app.get('/user/:name',function(req,res){
var myname = req.params.name;
//設定query參數物件裡面有個limit的參數名
var limit = req.query.limit;
res.send('<html><head></head><body><h1>'+myname+'向你說'+limit+'</h1></body></html>')
});


middleware 中介軟體

這是許多後端都會使用的,這可以幫助資料正確性並進行下一步。
Middleware WIKI
Middleware 觀念解說
當然 express 也有包含這功能。
next 是下一步的函數。
網頁會先經過 use 的確認才會進行下一步,下一步就是連到網頁並給它 index 的資訊。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var express = require('express');
var app = express();
app.get('/',function(req,res){
res.send('<html><head></head><body><h1>登入</h1></body></html>')
});
app.use(function(req,res,next){
consloe.log('會員登入')
//下一步
next();
});
app.get('/user',function(req,res){
res.send('<html><head></head><body><h1>index</h1></body></html>')
});
//監聽 port
var port = process.env.PORT || 3000;
app.listen(port);

結語

了解這個就發覺後端是怎樣運作的,有任何問題歡迎寫 MAIL: pp840405@gmail.com 一起共同討論。