在使用了koa和egg的路由后发现真的是太太太方便了,通过访问的路径来设置路由,通过路由来定位显示的页面。短短几行代码就把逻辑实现了。通过使用nodejs原生的方式可否实现页面的重定向呢,答案是肯定的,只不过实现的代码会比较多,不过要是简单接触过node的可以看懂。
在新建的文件夹下有一个www目录用来存放html页面,在根目录下新建一个test.js页面。在js文件中引入需要的http模块和path模块以及js模块。
在www目录下分别存在index.html、about.html、list.html三个文件,里面随便写点html代码。
代码显示如下:
/**
* 路径的分发
* 1、req对象是Class:http.IncomingMessage的实例对象
* 2、res对象是Class: http.ServerResponse的实例对象
*/
const http = require('http');
const path = require('path');
const fs = require('fs');
http.createServer((req,res)=>{
if(req.url.startsWith('/index')){
fs.readFile(path.join(__dirname,'www','index.html'),'utf8',(err,fileContent)=>{
if(err){
res.end('server error');
}else{
res.end(fileContent);
}
})
}else if(req.url.startsWith('/about')){
fs.readFile(path.join(__dirname,'www','about.html'),'utf8',(err,fileContent)=>{
if(err){
res.end('server error');
}else{
res.end(fileContent);
}
})
}else if(req.url.startsWith('/list')){
fs.readFile(path.join(__dirname,'www','list.html'),'utf8',(err,fileContent)=>{
if(err){
res.end('server error');
}else{
res.end(fileContent);
}
})
}
}).listen(3000);
通过监听3000端口可以访问各个页面。
通过上面的代码我们发现代码冗余的太多了,我们可以把重复的代码进行抽取,抽取成函数,当需要使用的时候进行调用就可以了
调整后的代码如下所示:
/**
* 路径的分发
* 1、req对象是Class:http.IncomingMessage的实例对象
* 2、res对象是Class: http.ServerResponse的实例对象
*/
const http = require('http');
const path = require('path');
const fs = require('fs');
//抽取函数
//这里传入两个参数,url是传入的html页面的名字,res是传入的response对象。
let readFile = (url,res)=>{
fs.readFile(path.join(__dirname,'www',url),'utf8',(err,fileContent)=>{
if(err){
res.end('server error');
}else{
res.end(fileContent);
}
})
}
http.createServer((req,res)=>{
if(req.url.startsWith('/index')){
readFile('index.html',res);
}else if(req.url.startsWith('/about')){
readFile('about.html',res);
}else if(req.url.startsWith('/list')){
readFile('list.html',res);
}else{
res.writeHead(200,{
'Content-type':'text/plain;charset=utf8'
});
res.end('访问页面不存在...')
}
}).listen(3000);
是不是简单很多~~~