本篇文章將解說如何使用node.js 透過程式判別http 伺服器所提供的路由處理方法。範例如下,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var server, ip = "127.0.0.1", | |
port = 1337, | |
http = require('http'), | |
url = require('url'); | |
server = http.createServer(function (req, res) { | |
console.log(req.url); | |
res.writeHead(200, { | |
'Content-Type': 'text/plain' | |
}); | |
res.end('hello world\n'); | |
}); | |
server.listen(port, ip); | |
console.log("Server running at http://" + ip + ":" + port); |
url 模組就跟如同他的命名一般,專門處理url 字串處理,裡面提供了許多方法來解決路徑上的問題。 因為從瀏覽器發出的要求路徑可能會帶有多種需求,或者GET 參數組合等。因此我們需要將路徑單純化,取用路徑部分的資料即可,例如使用者可能會送出 http://127.0.0.1:1337/test?send=1 ,如果直接信任**req.url** 就會收到結果為 /test?send=1 ,所以需要透過url 模組的方法將路徑資料過濾。
在這邊使用url.parse 的方法,裡面帶入網址格式資料,會回傳路徑資料。為了後需方便使用,將回傳的資料設定到path 變數當中。在回傳的路徑資料,裡面包含資訊,如下圖,
這邊只需要使用單純的路徑要求,直接取用path.pathname ,就可以達到我們的目的。
最後要做路徑的判別,在不同的路徑可以指定不同的輸出,在範例中有三個可能結果,第一個從瀏覽器輸入/index 就會顯示 index 結果, /test 就會呈現出 test 頁面,最後如果都不符合預期的輸入會直接顯示 default 的頁面,最後的預防可以讓瀏覽器不會出現非預期結果,讓程式的可靠性提昇,底下為測試結果。
留言
張貼留言