Nodejs原生实现路由
实现单页面跳转 类似tab选项卡但不是tab选项卡 通过改变res.url地址实现跳转
const http=require('http');//获取http模块
const fs =require('fs')//获取fs文件系统模块
const host='localhost';
const port=3000
//后端路由就是是一个web服务器
//路由 路就是路径
http
.createServer((req,res,)=>{//创建服务器
// console.log(req.url)
res.writeHead(200,{//请求头
'Content-type':'text/html;charset=utf8'
})
switch(req.url){//判断地址的改变
case '/hello':
fs.readFile('./static/hello.html','utf8',(error,docs)=>{//实现跳转的内容
// console.log(docs)
res.write(docs)
res.end()
})
break;
case '/1.png':
fs.readFile('./static/1.png',(error,docs)=>{
// console.log(docs)
res.write(docs,'binary')
res.end()
})
break;
case '/hi':
fs.readFile('./static/hi.html','utf8',(error,docs)=>{
// console.log(docs)
res.write(docs)
res.end()
})
break;
case '/hi.js':
fs.readFile('./static/hi.js','utf8',(error,docs)=>{
// console.log(docs)
res.write(docs)
res.end()
})
break;
}
})
.listen(port,host,()=>{
console.log(`服务器运行于:http://${host}:${port}`)
})
nodejs原生路由所有的文件包括图片等全部要后端发送给前端才能进行渲染,其过程比较复杂繁琐