基础
路由是用于处理不同方法和路径的HTTP请求的,根据路径返回不同页面或者不同的接口内容。可以实现页面跳转、接口调用等各种需求。
const fs=require("fs")
const http = require("http")
http.createServer(req,res)=>{
const myURl= new URL(req.url,"http://127.0.0.1")
switch(myURl.pathname){
//如果路径是/login 则读取static/login.html文件
case "/login":
res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"})
res.write(fs.readFileSync("./static/login.html"),"utf-8")
break;
//如果路径是/home 则读取static/home.html文件
case "/home":
res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"})
res.write(fs.readFileSync("./static/home.html"),"utf-8")
break;
//如果路径是其他的 则读取static/404.html文件
default:
res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"})
res.write(fs.readFileSync("./static/404.html"),"utf-8")
}
res.end()
)}.linsten(3000,()=>{
console.log("server start")
})
以对象的方式存储路径
const myURl= new URL(req.url,"http://127.0.0.1")
const route={
"/login":(req,res)=>{
res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"})
res.write(fs.readFileSync("./static/login.html"),"utf-8")
},
"/home":(req,res)=>{
res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"})
res.write(fs.readFileSync("./static/home.html"),"utf-8")
},
"/404":(req,res)=>{
res.writeHead(200,{"Content-Type":"text/html;charset=utf-8"})
res.write(fs.readFileSync("./static/404.html"),"utf-8")
},
}
try{
route[myURL.pathname](req,res)
}
catch(error){
route["/404"](req,res)
}
res.end()