从零开始学Node.js(九):Node.js封装静态web服务、路由
第九节涉及到的项目文件目录如下所示。
封装静态web服务
本节所要封装的静态web服务呢,是基于从零开始学Node.js(八)中的小项目。主要过程分为这样几个过程:
-
封装web服务器的主要代码:在module文件夹下创建route.js文件,将原项目app.js中创建web服务器的代码封装到route.js中的static函数中。
-
此时需要注意的是,可能会涉及修改路径。
route.js代码如下所示。
const fs=require('fs');
const path=require('path');
const url=require('url');
//私有方法
let getFileMime = function(extname){
var data=fs.readFileSync('./data/mime.json');
let mimeObj=JSON.parse(data.toString());
return mimeObj[extname];
}
exports.static=function(request,response,staticPath){
//获取地址
let pathname=url.parse(request.url).pathname;
pathname=pathname=='/'?'/index.html':pathname;
//获取后缀名
let extname=path.extname(pathname);
//通过fs模块读取文件
if(pathname!='/favicom.ico'){
fs.readFile('./'+staticPath+pathname,(err,data)=>{
if(err){
response.writeHead(404,{'Content-Type': 'text/html;charset="utf-8"'});
response.end("该页面不存在");
}
let mime=path.extname(extname);
response.writeHead(200, {'Content-Type': ''+mime+';charset="utf-8"'});
response.end(data);
})
}
}
app.js代码如下所示。通过require引入我们自定义的route模块,然后调用static方法创建静态web服务。
const http = require('http');
const routes=require('./module/route');
http.createServer(function (request, response) {
//创建静态web服务
routes.static(request,response,'static');
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
路由
路由指的是针对不同请求的URL,处理不同的业务逻辑。
路由时一个URI和一个特定的HTTP方法(get/post等)组成的,涉及到应用如何响应客户端对某个网站节点的访问。
比如说,http://域名//login
,处理登录的业务逻辑,那么这个就是路由。路由的实现需要引入url模块。
新建routetest.js,通过url获取请求路径pathname,然后通过if语句进行判断,执行相应的业务逻辑。提示:对于访问站点下的静态资源,其实我们都将相关方法封装到了route模块中。
const http = require('http');
const routes = require('./module/route');
const url=require('url');
http.createServer(function (request, response) {
//创建静态web服务
routes.static(request, response, 'static');
//路由
let pathname = url.parse(request.url).pathname;
if (pathname == '/login') {
response.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
response.end("执行登录");
} else if (pathname == '/register') {
response.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
response.end("执行注册");
}else{
response.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' });
response.end("页面不存在~");
}
}).listen(8081);
console.log('Server running at http://127.0.0.1:8081/');
启动之后,发现127.0.0.1:8081/index.html
显示页面不存在,我们写的这个127.0.0.1:8081/login
等等可以正常运行,这是为啥呢?我们知道访问index.html的功能实际上该静态服务器本身是可以处理的(封装到route中了),显示页面不存在可以说明创建静态服务器还没有完成,直接跑到了下面这个判断pathname的过程中了。这又是为啥呢?因为route.js中读取文件的方法是个异步方法,所以我们需要把程序改成同步的。
修改route.js内容。注意我们将readFile
改成了readFileSync
!
const fs = require('fs');
const path = require('path');
const url = require('url');
//私有方法
let getFileMime = function (extname) {
var data = fs.readFileSync('./data/mime.json');
let mimeObj = JSON.parse(data.toString());
return mimeObj[extname];
}
exports.static = function (request, response, staticPath) {
//获取地址
let pathname = url.parse(request.url).pathname;
console.log(pathname);
pathname = pathname == '/' ? '/index.html' : pathname;
console.log(pathname);
//获取后缀名
let extname = path.extname(pathname);
//通过fs模块读取文件
if (pathname != '/favicom.ico') {
try {
let data = fs.readFileSync('./' + staticPath + pathname);
if (data) {
let mime = getFileMime(extname);
response.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
response.end(data);
}
} catch (error) {
}
}
}