上一篇学习已经可以展示一个网站的首页,但是网站不仅仅只有一个网页(单页应用除外),还需要其他的页面。在运行上面程序的时候可以发现,在控制台输入node 路径\index.js时,并不会执行onRequest函数,只有在刷新浏览器时才会执行。在首页中点击超链接时直接执行onRequest函数。由于html文件是存放在tpl文件夹中,如此一来造成realpath的路径不能再通过config.root + pathname得到,所以server.js文件需要改造一下。
// server.js
var config = require('./common/config');
var http = require('http');
var fs = require('fs');
var url = require('url');
var path = require('path');
var FServer = require('./server/FServer');
function index(){
var indexPath = config.ui + '/index.html';
fs.exists(indexPath, function(exists){
if( !exists ) {
throw err;
} else {
fs.readFile(indexPath, function(err, data){
if (err) {
throw err;
} else {
function onRequest(req, res){
// 取得文件路径
var pathname = url.parse(req.url).pathname;
// 获取文件扩展名(包含前置.)
var extname = path.extname( pathname );
var type = extname.slice(1);
// 获取下载文件在磁盘上的路径,
var realPath = config.root + pathname;
if ( extname === '' ) {
res.writeHead(200, {'Content-Type':'text/html'});
res.write(data);
res.end();
} else{
// 添加一次判断
if( type == 'html' )
realPath = config.root + '/tpl' + pathname;
}
FServer.filesLoad(realPath, type, req, res);
}
}
http.createServer(onRequest).listen(config.port);
}
})
}
})
}
exports.index = index;
改造之后就可以在原网页中添加金泰的页面了。