標籤:讀取檔案 res localhost ring tle replace ports style 輸出
1. 路由選擇過程
處理不同的HTTP請求在我們的代碼中是一個不同的部分,叫做“路由選擇”。
那麼,我們接下來就創造一個叫做 路由 的模組吧。我們需要查看HTTP請求,從中提取出請求的URL以及GET/POST參數。
url.parse(string).query | url.parse(string).pathname | | | | | ------ -------------------http://localhost:8888/start?foo=bar&hello=world --- ----- | | | | querystring(string)["foo"] | | querystring(string)["hello"]
2. 路由選擇實現代碼
建立屬於伺服器端的路由檔案router.js
1 //-----------------router.js--------------------------------2 module.exports={3 login:function(req,res){4 res.write("我是login方法");5 },6 register:function(req,res){7 res.write("我是註冊方法");8 }9 }
服務端調用路由,方式和上一節課《nodejs進階2--函數模組調用》中最後提到的字串調用函數一樣。
1 //---------4_router.js----------- 2 var http = require(‘http‘); 3 var url = require(‘url‘); 4 var router = require(‘./router‘); 5 http.createServer(function (request, response) { 6 response.writeHead(200, {‘Content-Type‘: ‘text/html; charset=utf-8‘}); 7 if(request.url!=="/favicon.ico"){ 8 var pathname = url.parse(request.url).pathname;//得到請求的路徑 9 console.log(pathname);10 pathname = pathname.replace(/\//, ‘‘);//替換掉前面的/11 console.log(pathname);12 router[pathname](request,response);13 response.end(‘‘);14 }15 }).listen(8000);16 console.log(‘Server running at http://127.0.0.1:8000/‘);
上面我們用到了node內建模組url。url.path(urlStr):將一個URL字串轉換成對象並返回。
3. url.path(urlStr)執行個體
下面展示兩個url.parse的執行個體
例1. url.parse(‘http://stackoverflow.com/questions/17184791‘).pathname
結果為:"/questions/17184791"
例2:
1 var url = require(‘url‘); 2 var a = url.parse(‘http://example.com:8080/one?a=index&t=article&m=default‘); 3 console.log(a); 4 5 //輸出結果: 6 { 7 protocol : ‘http‘ , 8 auth : null , 9 host : ‘example.com:8080‘ ,10 port : ‘8080‘ ,11 hostname : ‘example.com‘ ,12 hash : null ,13 search : ‘?a=index&t=article&m=default‘,14 query : ‘a=index&t=article&m=default‘,15 pathname : ‘/one‘,16 path : ‘/one?a=index&t=article&m=default‘,17 href : ‘http://example.com:8080/one?a=index&t=article&m=default‘18 }4. 向頁面輸出html檔案
對於一般的get請求,例如localhost/login 我們需要給瀏覽器輸出個頁面login.html,那我們怎麼做呢?
首先我們新增兩個頁面
1.login.html
1 <html>2 <head>3 </head>4 <body>5 登入:6 <p>這是一個段落</p>7 <h1>樣式1</h1>8 </body>9 <html>
2.register.html
1 <html>2 <head>3 </head>4 <body>5 註冊:6 <p>這是一個段落</p>7 <h1>樣式1</h1>8 </body>9 <html>
讀取檔案的方法,我們放到檔案models/file.js裡
1 //-------------models/file.js------------------------- 2 var fs= require(‘fs‘); 3 module.exports={ 4 readfile:function(path,callback){ //非同步讀檔案,需要傳入回呼函數 5 fs.readFile(path, function (err, data) { 6 if (err) { 7 console.log(err); 8 }else{ 9 callback(data);10 }11 });12 console.log("非同步方法呼叫執行完畢");13 },14 readfileSync:function(path){ //同步讀取15 var data = fs.readFileSync(path,‘utf-8‘);16 console.log("同步方法執行完畢");17 return data; 18 }19 }
router.js需要調用檔案讀取方法,把兩個頁面html檔案讀取出內容並輸出到response。需要注意的是:res.end()這句話的位置,如果用非同步讀檔案的方法就不能放到server建立那塊了
1 //-----------------router.js-------------------------------- 2 var file = require(‘./models/file‘); 3 module.exports={ 4 login:function(req,res){ 5 var callback=function(data){ 6 res.write(data); 7 res.end(); 8 } 9 file.readfile(‘./views/login.html‘,callback);//使用非同步讀取10 },11 register:function(req,res){12 var data=file.readfileSync(‘./views/register.html‘);//使用同步讀取13 res.write(data);14 res.end();15 }16 }
我們重新運行:node 4_router.js。分別在瀏覽器輸入http://localhost:8000/login 和http://localhost:8000/register ,輸出了login.html和register.html頁面的內容。
nodejs進階3-路由處理