http—服务型模块
模块就是用来提供web服务的,类似于apache服务器
接下来讲一下路由的功能案例
1.首先,http创建一个服务,需要有 请求 和 响应
—所有从浏览器传过来的数据从req里找
—所有传给浏览器的东西在res里找
2.这个服务的实例需要监听一个端口
3.自定义一个读取文件的模块
4.判断访问的路径,后端来返回不同文件的内容
这是接下来代码的文件目录
/public/html/index.html
<link rel="stylesheet" href="index.css">
<h1>这里是首页</h1>
/public/html/news.html
<script src="404.js"></script>
<h1>这里是新闻页</h1>
/public/html/404.html
<h1>404 您访问的页面不存在。</h1>
/public/js/404.js
setTimeout(function(){
location.href='/';//类unix操作系统中 绝对路径从根目录开始 /
},3000);
/public/css/index.css
h1{
color:red;
}
/lib/readfile.js
//读取文件
const fs=require('fs');
const path=require('path');
//封装读取文件函数
function readFile(){
// 绝对路径 返回上一级目录 展开传入的参数
let url=path.join(__dirname,'..',...arguments);
// console.log(url);//读取文件的绝对路径
//读写文件都是阻塞操作,用异步操作来解决
return new Promise((resolve,reject)=>{
fs.readFile(url,'utf8',(err,data)=>{//回调函数错误前置
err && reject(err);
resolve(data);
})
})
}
module.exports=readFile;//导出模块
这是最重要的一个文件2.router.js
switch判断的部分即是路由部分
//路由:返回一个页面给用户
const http=require('http');
const path=require('path');
const readFile=require('./lib/readfile');//引入自定义模块 注:填相对路径,不写后缀名
const port=8888;
const server=http.createServer((req,res)=>{
// req request 请求 ---浏览器到服务器
// res response 响应 ---服务器到浏览器
let url=path.join(req.headers.host,req.url);
console.log(`${req.method} ${url}`);
res.writeHead(200,{'content-type':'text/html;charset=utf-8'});//设置响应头
//路由控制的是访问的路径
//路径能访问到什么是由后端来控制的
switch(req.url){//判断访问的路径
case '/':
readFile('public','html','index.html').then(data=>{
res.end(data);//响应结束 并且把结果返回给浏览器
}).catch(err=>{
res.end(err);
})
break;
case '/news':
readFile('public','html','news.html').then(data=>{
res.end(data);//响应结束 并且把结果返回给浏览器
}).catch(err=>{
res.end(err);
})
break;
case '/404.js':
readFile('public','js','404.js').then(data=>{
res.end(data);//响应结束 并且把结果返回给浏览器
}).catch(err=>{
res.end(err);
})
break;
case '/index.css':
res.writeHead(200,{'content-type':'text/css;charset=utf-8'});
readFile('public','css','index.css').then(data=>{
res.end(data);//响应结束 并且把结果返回给浏览器
}).catch(err=>{
res.end(err);
})
break;
default:
readFile('public','html','404.html').then(data=>{
res.end(data);//响应结束 并且把结果返回给浏览器
}).catch(err=>{
res.end(err);
})
}
})
server.listen(port,()=>{//监听一个端口
console.log(`server is running on http://localhost:${port}`);
})
nodejs运行环境下打开2.router.js
通过访问不同的路径地址,来访问不同的页面
注意:
路由控制的是访问的路径
路径能访问到什么是由后端来控制的
效果:
访问http://localhost:8888
访问http://localhost:8888/news
访问http://localhost:8888/aaa
同时引入了404.js文件,3秒后调转至主页
你们一定还有一个疑问?不是常说前端写相对路径,后端写绝对路径吗?
在404.html页面script标签引入了404.js文件,其实就是向服务器发送了请求,路由就去判断请求的路径,是由路由来控制访问的路径,再有后端来控制路径能访问到什么。