Node.js —— 使用http模組建立靜態web伺服器及其路由
阿新 • • 發佈:2018-12-23
1、使用http建立靜態web伺服器
解析使用者請求的 url,將 url 的路徑名稱和靜態目錄的名稱進行拼接,若 url 指定檔案存在,則返回該檔案內容
function staticRoot(staticPath, req, res){
var pathObj = url.parse(req.url, true);
var filePath = path.join(staticPath, pathObj.pathname);
fs.readFile(filePath,'binary', function(err, content){
if(err){
res.writeHead('404' , 'Not Found');
res.end()
}else{
res.writeHead(200, 'Ok');
res.write(content, 'binary');
res.end()
}
})
}
2、設定路由
var routes = {
'/a': function(req, res){
res.end('match /a')
},
'/b': function(req, res){
res.end(JSON.stringify(req.query))
},
'/search' : function(req, res){
res.end('username='+req.body.username+',password='+req.body.password)
}
};
3、建立路由
1、如果pathname與動態路由routes相匹配,則按rounts的要求執行,否則執行static中的內容
2、若傳送附帶搜尋條件的GET請求,則將 query 繫結到 req 上
3、若傳送附帶搜尋條件的POST請求,則監聽資料內容,將資料內容存放 body 中,用 parseBody(body) 將其進行解析後繫結到 req 上
function routePath (req, res){
var pathObj = url.parse(req.url, true);
var handleFn = routes[pathObj.pathname];
if(handleFn){
req.query = pathObj.query;// 將 query 繫結到 req 上
var body = '';
// 監聽 POST 的資料內容
req.on('data', function(chunk){
body += chunk
}).on('end', function(){
req.body = parseBody(body);
handleFn(req, res)
})
}else {
staticRoot(path.resolve(__dirname, 'static'), req, res);
}
}
function parseBody(body){
console.log(body);
var obj = {};
body.split('&').forEach(function(str){
obj[str.split('=')[0]] = str.split('=')[1]
});
return obj
}
4、完整程式碼
var http = require('http');
var path = require('path');
var fs = require('fs');
var url = require('url');
var routes = {
'/a': function(req, res){
res.end('match /a')
},
'/b': function(req, res){
res.end(JSON.stringify(req.query))
},
'/search': function(req, res){
res.end('username='+req.body.username+',password='+req.body.password)
}
};
var server = http.createServer(function(req, res){
routePath(req, res)// 對傳送過來的url進行解析
}).listen(8080);
function routePath(req, res){
var pathObj = url.parse(req.url, true);
var handleFn = routes[pathObj.pathname];
if(handleFn){
req.query = pathObj.query;// 將 query 繫結到 req 上
var body = '';
req.on('data', function(chunk){
body += chunk
}).on('end', function(){
req.body = parseBody(body);
handleFn(req, res)
})
}else {
staticRoot(path.resolve(__dirname, 'static'), req, res);
}
}
function staticRoot(staticPath, req, res){
var pathObj = url.parse(req.url, true);
var filePath = path.join(staticPath, pathObj.pathname);
fs.readFile(filePath,'binary', function(err, content){
if(err){
res.writeHead('404', 'Not Found');
return res.end()
}
res.writeHead(200, 'Ok');
res.write(content, 'binary');
res.end()
})
}
function parseBody(body){
console.log(body);
var obj = {};
body.split('&').forEach(function(str){
obj[str.split('=')[0]] = str.split('=')[1]
});
return obj
}