nodejs配置路由

  • 这篇博客就使用原生的node来配置路由,涉及路由的基本跳转, 获取请求参数,页面路由和api接口路由的合并封装,直接上代码了

代码展示:

  • 页面路由(route.js)
// 设置路由转向
// 引入fs模块
const fs =require("fs")

// 渲染函数render
function render(res,path,type=""){//第三个参数为文件读取格式
// 设置响应头(文件和文字的读取格式)
res.writeHead(200, { "Content-Type": `${type?type:"text/html"};charset=utf8` })
res.write(fs.readFileSync(path), "utf-8")
res.end()
}

// 方法1 : 将路由的转向设置成一个函数
// function route(res , url){
// switch(url){
// case '/login':
// render(res,'./static/login.html')
// break;
// case '/home':
// render(res , './static/home.html')
// break;
// default :
// render(res , './static/404.html')
// }
// }

// 方法2 : 将路由的转向设置成一个对象
const route = {
"/login":(req,res)=>{
render(res,"./static/login.html")
},
"/home":(req,res)=>{
render(res,"./static/home.html")
},
"/404":(req,res)=>{
res.writeHead(404, { "Content-Type": "text/html;charset=utf8" })
res.write(fs.readFileSync("./static/404.html"), "utf-8")
res.end()
},
}

module.exports = route
  • api接口路由,get,post(api.js)
// api接口路由 

// 创建页面的渲染函数
function render(res,data,type=""){//接收3个参数()
res.writeHead(200, { "Content-Type": `${type?type:"application/json"};charset=utf8` })
res.write(data)
res.end()
}
// api接口路由的设置
const apiRouter = {
"/api/login":(req,res)=>{//get请求
// 获取url上的参数
const myURL = new URL(req.url,"http://127.0.0.1")
console.log(myURL.searchParams);
// 设置登录判断
if(myURL.searchParams.get("username")==="lam" && myURL.searchParams.get("password")==="123"){
render(res,`{"ok":1}`)//登陆成功
}else{
render(res,`{"ok":0}`)//登陆失败
}

},

"/api/loginpost":(req,res)=>{//post请求
//获取参数呢?(相较于get请求要复杂一点)
var post = ""
req.on("data",chunk=>{//chunk数据(响应体数据,账号密码)写入
// console.log(chunk)
post+=chunk//一段一段的接收直到接收完成
})

req.on("end",()=>{
console.log(post)//输出我们接收到的数据(响应体)
post = JSON.parse(post)
if(post.username==="lam" && post.password==="123"){
render(res,`{"ok":1}`)//登陆成功
}else{
render(res,`{"ok":0}`)//登陆失败
}
})
}
}

module.exports = apiRouter
  • 服务器(server.js)
//首先引入http模块
const http = require("http")
var Router = {}//创建路由器用于接收拼接好的页面和api接口

//express use
function use(obj){
// 路由的拼接(页面路由与api接口)
Object.assign(Router,obj)
// 或者使用es6的拓展字符串...
// return Router = {...Router,...obj}
}

// 创建和启动服务器
function start(){
http.createServer((req, res) => {
// 获取到url上的参数
const myURL = new URL(req.url, "http://127.0.0.1")
// console.log(myURL.pathname)

try {//一定要使用try catch
Router[myURL.pathname](req,res)
} catch (error) {
Router["/404"](req,res)
}

}).listen(3000, () => {
console.log("服务器已启动,3000端口正在监听...")
})
}

// 暴露两种方法,路由的合并(注册)以及服务器的启动
exports.start = start
exports.use = use
  • 程序的启动文件(index.js)
// 程序的入口index

// 1.引入所有的路由(页面以及api接口)
const server = require("./server")//引入服务器
const route = require("./route")//页面路由
const api = require("./api")//api接口路由

// 2.注册路由(我们自己封装的函数,作路由拼接)
server.use(route)
server.use(api)

// 3.调用函数启动服务器
server.start()
  • 这里就展示一个页面-登陆页面实现获取请求参数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录页</title>
</head>
<body>
<h1>登录页</h1>
<div>
用户名:<input id="username"/>
密码:<input type="password" id="password"/>

<div>
<button id="login">登录-get</button>
<button id="loginpost">登录-post</button>
</div>
</div>
<script>
// 获取页面上的标签
var ologin = document.querySelector("#login")
var ologinpost = document.querySelector("#loginpost")
var username = document.querySelector("#username")
var password = document.querySelector("#password")

// 注册点击事件
ologin.onclick = ()=>{
// console.log(username.value,password.value)
// 使用fetch发送http请求
// 1.get请求(url携带用户名和密码参数)
fetch(`/api/login?username=${username.value}&password=${password.value}`)
.then(res=>res.text())//将返回的结果转变成字符串形式
.then(res=>{
console.log(res)//控制台输出渲染内容
})
}

ologinpost.onclick = ()=>{
// console.log(username.value,password.value)
// 使用fetch发送http请求
// 2.post请求(响应体携带用户名和密码参数)
fetch(`/api/loginpost`,{
method:"POST",
body:JSON.stringify({//设置响应体内容
username:username.value,//用户名
password:password.value//密码
}),
headers:{//设置响应头
"Content-Type":"application/json"
}
}).then(res=>res.text()).then(res=>{
console.log(res)
})
}
</script>
</body>
</html>

结果展示:

image

  • 上面的gif可以看到,页面会随着url的改动而跳转, 登陆成功返回{"ok":1},失败返回{"ok":0}