1、新建文件router.js
//fs模块
var fs = require('fs');
//path模块
var path = require('path');
/*nodejs自带的模块*/
//url模块
var url = require('url');
var getMime = function(extname, callback) { /*获取后缀名的方法*/
fs.readFile('./mime.json', function (err, data) {
if (err) {
console.log('mime.json文件不存在');
return false;
}
var Mimes = JSON.parse(data.toString());//把json字符串转换为json对象
var result = Mimes[extname] || 'text/html';
callback(result);
});
}
exports.statics = function (req, res, baseDir) {//注:baseDir是一个变量,不是常量
var pathname = url.parse(req.url).pathname;//使用url.parse()进行对请求的url进行过滤
console.log(pathname);
if (pathname == '/') {
pathname = '/index.html';
/*默认加载的首页*/
}
//获取文件的后缀名
var extname = path.extname(pathname);
if (pathname != '/favicon.ico') { /*过滤请求favicon.ico*/
//console.log(pathname);
//文件操作获取 static下面的index.html
fs.readFile(baseDir + '/' + pathname, function (err, data) {//在static目录下寻找文件
if (err) { /*么有这个文件*/
console.log('404');
fs.readFile(baseDir + '/' + '404.html', function (error, data404) {
if (error) {
console.log(error);
}
res.writeHead(404, {"Content-Type": "text/html;charset='utf-8'"});
res.write(data404);
res.end();
/*结束响应*/
})
} else { /*返回这个文件*/
//调用函数,传入EventEmitter
getMime(extname, function (mime) {//这个mime是经过回调函数处理之后返回的
res.writeHead(200, {"Content-Type": "" + mime + ";charset='utf-8'"});
res.write(data);
res.end();
/*结束响应*/
});
}
})
}
}
2、00service1.js(只负责调用,此时该文件内容非常简洁)
//引入http模块
var http=require('http');
var router = require('./model/router.js')
http.createServer(function(req,res){
router.statics(req,res,'static');
}).listen(8002);
3、路由简单示例
//引入http模块
var http=require('http');
var url = require('url')
/*
* 路由:指的是针对不同的URL,处理不同的业务逻辑
* */
var router = require('./model/router.js')
http.createServer(function(req,res){
var pathname = url.parse(req.url).pathname
if(pathname=='/login'){
res.end('login')
}else if(pathname=='/register'){
res.end('registe')
}else if(pathname=='/order'){
res.end('order')
}else{
res.end('index')
}
res.end();
}).listen(8002);