【Node.js】路由

news2025/4/17 4:25:42

基础使用

写法一:

// server.js
const http  = require('http');
const fs = require('fs');
const route  = require('./route')
http.createServer(function (req, res) {
  const myURL = new URL(req.url, 'http://127.0.0.1')
  route(res, myURL.pathname)
  res.end()
}).listen(3000, ()=> {
  console.log("server start")
})
// route.js
const fs = require('fs')
function route(res, pathname) {
  switch (pathname) {
    case '/login':
      res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' })
      res.write(fs.readFileSync('./static/login.html'), 'utf-8')
      break;
    case '/home':
      res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' })
      res.write(fs.readFileSync('./static/home.html'), 'utf-8')
      break
    default:
      res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' })
      res.write(fs.readFileSync('./static/404.html'), 'utf-8')
      break
  }
}
module.exports = route

写法二:

// route.js
const fs = require('fs')

const route = {
  "/login": (res) => {
    res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' })
    res.write(fs.readFileSync('./static/login.html'), 'utf-8')
  },
  "/home": (res) => {
    res.writeHead(200, { 'Content-Type': 'text/html;charset=utf-8' })
    res.write(fs.readFileSync('./static/home.html'), 'utf-8')
  },
  "/404": (res) => {
    res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' })
    res.write(fs.readFileSync('./static/404.html'), 'utf-8')
  },
  "/favicon.ico": (res) => {
    res.writeHead(200, { 'Content-Type': 'image/x-icon;charset=utf-8' })
    res.write(fs.readFileSync('./static/favicon.ico'))
  }
}
module.exports = route
// server.js
const http  = require('http');
const fs = require('fs');
const route  = require('./route')
http.createServer(function (req, res) {
  const myURL = new URL(req.url, 'http://127.0.0.1')
  try {
    route[myURL.pathname](res)
  } catch (error) {
    route['/404'](res)
  }
  res.end()
}).listen(3000, ()=> {
  console.log("server start")
})

注册路由

// api.js
function render(res, data, type = "") {
  res.writeHead(200, { 'Content-Type': `${type ? type : 'application/json'};charset=utf-8` })
  res.write(data)
  res.end()
}
const apiRouter = {
  'api/login':(res)=> [
    render(res, `{ok:1}`)
  ]
}
module.exports = apiRouter
// route.js
const fs = require('fs')

function render(res, path, type="") {
  res.writeHead(200, { 'Content-Type': `${type?type:'text/html'};charset=utf-8` })
  res.write(fs.readFileSync(path), 'utf-8')
  res.end()
}

const route = {
  "/login": (res) => {
    render(res, './static/login.html')
  },
  "/home": (res) => {
    render(res, './static/home.html')
  },
  "/404": (res) => {
    res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' })
    res.write(fs.readFileSync('./static/404.html'), 'utf-8')
    res.end()
  },
  "/favicon.ico": (res) => {
    render(res, './static/favicon.ico', 'image/x-icon')
  }
}
module.exports = route
// server.js
const http = require('http');
const Router = {}
const use = (obj) => {
  Object.assign(Router, obj)
}
const start = () => {
  http.createServer(function (req, res) {
    const myURL = new URL(req.url, 'http://127.0.0.1')
    try {
      Router[myURL.pathname](res)
    } catch (error) {
      Router['/404'](res)
    }

  }).listen(3000, () => {
    console.log("server start")
  })
}
exports.start = start
exports.use = use
// index.js
const server = require('./server');
const route = require('./route');
const api = require('./api');
// 注册路由
server.use(route)
server.use(api)
server.start()

get 和 post

// api.js
function render(res, data, type = "") {
  res.writeHead(200, { 'Content-Type': `${type ? type : 'application/json'};charset=utf-8` })
  res.write(data)
  res.end()
}
const apiRouter = {
  '/api/login': (req,res) => {
    const myURL = new URL(req.url, 'http:/127.0.0.1')
    if(myURL.searchParams.get('username') === 'admin' && myURL.searchParams.get('password') === '123456') {
      render(res, `{"ok":1)`)
    } else {
      render(res, `{"ok":0}`)
    }
  },
  '/api/loginpost': (req, res) => {
    let post = ''
    req.on('data', chunk => {
      post += chunk

    })
    req.on('end', () => {
      console.log(post)
      post = JSON.parse(post)
      if(post.username === 'admin' && post.password === '123456') {
        render(res, `{"ok":1}`)
      }else {
        render(res, `{"ok":0}`)
      }
    })
  }
}
module.exports = apiRouter
// route.js
const fs = require('fs')

function render(res, path, type="") {
  res.writeHead(200, { 'Content-Type': `${type?type:'text/html'};charset=utf-8` })
  res.write(fs.readFileSync(path), 'utf-8')
  res.end()
}

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=utf-8' })
    res.write(fs.readFileSync('./static/404.html'), 'utf-8')
    res.end()
  },
  "/favicon.ico": (req,res) => {
    render(res, './static/favicon.ico', 'image/x-icon')
  }
}
module.exports = route
// server.js
const http = require('http');
const Router = {}
const use = (obj) => {
  Object.assign(Router, obj)
}
const start = () => {
  http.createServer(function (req, res) {
    const myURL = new URL(req.url, 'http://127.0.0.1')
    try {
      Router[myURL.pathname](req, res)
    } catch (error) {
      Router['/404'](req, res)
    }

  }).listen(3000, () => {
    console.log("server start")
  })
}
exports.start = start
exports.use = use
// index.js
const server = require('./server');
const route = require('./route');
const api = require('./api');
// 注册路由
server.use(route)
server.use(api)
server.start()
<!-- login.html -->
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div>
    用户名:<input type="text" class="username">
  </div>
  <div>
    密码:<input type="password" class="password">
  </div>
  <div>
    <button class="login">登录-get</button>
    <button class="loginpost">登录-post</button>
  </div>
  <script>
    const ologin = document.querySelector('.login')
    const ologinpost = document.querySelector('.loginpost')
    const password = document.querySelector('.password')
    const username = document.querySelector('.username')
    // get 请求
    ologin.onclick = () => {
      // console.log(username.value, password.value)
      fetch(`/api/login?username=${username.value}&password=${password.value}`)
        .then(res => res.text())
        .then(res => {
          console.log(res)
        })
    }
    // post 请求
    ologinpost.onclick = () => {
      fetch('api/loginpost',{
        method: 'post',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          username: username.value,
          password: password.value
        })
      }).then(res => res.text())
        .then(res=> {
          console.log(res)
        })
    }
  </script>
</body>

</html>

静态资源管理

成为静态资源文件夹static,可以直接输入类似于login.html或者login进行访问(忽略static/)。

在这里插入图片描述

在这里插入图片描述

<!-- login.html -->
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="/css/login.css">
</head>

<body>
  <div>
    用户名:<input type="text" class="username">
  </div>
  <div>
    密码:<input type="password" class="password">
  </div>
  <div>
    <button class="login">登录-get</button>
    <button class="loginpost">登录-post</button>
  </div>
  <script src="/js/login.js"></script>
</body>

</html>
/* login.css */
div {
  background-color: pink;
}
// login.js
const ologin = document.querySelector('.login')
const ologinpost = document.querySelector('.loginpost')
const password = document.querySelector('.password')
const username = document.querySelector('.username')
// get 请求
ologin.onclick = () => {
  // console.log(username.value, password.value)
  fetch(`/api/login?username=${username.value}&password=${password.value}`)
    .then(res => res.text())
    .then(res => {
      console.log(res)
    })
}
// post 请求
ologinpost.onclick = () => {
  fetch('api/loginpost', {
    method: 'post',
    headers: {
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      username: username.value,
      password: password.value
    })
  }).then(res => res.text())
    .then(res => {
      console.log(res)
    })
}
// api.js
function render(res, data, type = "") {
  res.writeHead(200, { 'Content-Type': `${type ? type : 'application/json'};charset=utf-8` })
  res.write(data)
  res.end()
}
const apiRouter = {
  '/api/login': (req, res) => {
    const myURL = new URL(req.url, 'http:/127.0.0.1')
    if (myURL.searchParams.get('username') === 'admin' && myURL.searchParams.get('password') === '123456') {
      render(res, `{"ok":1)`)
    } else {
      render(res, `{"ok":0}`)
    }
  },
  '/api/loginpost': (req, res) => {
    let post = ''
    req.on('data', chunk => {
      post += chunk

    })
    req.on('end', () => {
      console.log(post)
      post = JSON.parse(post)
      if (post.username === 'admin' && post.password === '123456') {
        render(res, `{"ok":1}`)
      } else {
        render(res, `{"ok":0}`)
      }
    })
  }
}
module.exports = apiRouter
// index.js
const server = require('./server');
const route = require('./route');
const api = require('./api');
// 注册路由
server.use(route)
server.use(api)
server.start()
// route.js
const fs = require('fs')
const mime = require('mime')
const path = require('path')
function render(res, path, type = "") {
  res.writeHead(200, { 'Content-Type': `${type ? type : 'text/html'};charset=utf-8` })
  res.write(fs.readFileSync(path), 'utf-8')
  res.end()
}

const route = {
  "/login": (req, res) => {
    render(res, './static/login.html')
  },
  "/": (req, res) => {
    render(res, './static/home.html')
  },
  "/home": (req, res) => {
    render(res, './static/home.html')
  },
  "/404": (req, res) => {
    // 校验静态资源能否读取
    if(readStaticFile(req, res)) {
      return 
    }
    res.writeHead(404, { 'Content-Type': 'text/html;charset=utf-8' })
    res.write(fs.readFileSync('./static/404.html'), 'utf-8')
    res.end()
  },
  // 静态资源下没有必要写该 ico 文件加载
  // "/favicon.ico": (req, res) => {
  //   render(res, './static/favicon.ico', 'image/x-icon')
  // }
}

// 静态资源管理
function readStaticFile(req, res) {
  const myURL = new URL(req.url, 'http://127.0.0.1:3000')
  // __dirname 获取当前文件夹的绝对路径  path 有以统一形式拼接路径的方法,拼接绝对路径
  const pathname = path.join(__dirname, '/static', myURL.pathname)
  if (myURL.pathname === '/') return false
  if (fs.existsSync(pathname)) {
    // 在此访问静态资源
    // mime 存在获取文件类型的方法
    // split 方法刚好截取文件类型
    render(res, pathname, mime.getType(myURL.pathname.split('.')[1]))
    return true
  } else {
    return false
  }
}
module.exports = route
// server.js
const http = require('http');
const Router = {}
const use = (obj) => {
  Object.assign(Router, obj)
}
const start = () => {
  http.createServer(function (req, res) {
    const myURL = new URL(req.url, 'http://127.0.0.1')
    try {
      Router[myURL.pathname](req, res)
    } catch (error) {
      Router['/404'](req, res)
    }

  }).listen(3000, () => {
    console.log("server start")
  })
}
exports.start = start
exports.use = use

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1085606.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Java从resources文件下载文档,文档没有后缀名

业务场景&#xff1a;因为公司会对excel文档加密&#xff0c;通过svn或者git上传代码也会对文档进行加密&#xff0c;所以这里将文档后缀去了&#xff0c;这样避免文档加密。 实现思路&#xff1a;将文档去掉后缀&#xff0c;放入resources下&#xff0c;获取输入流&#xff0…

12V手电钻保护板如何接线演示

爱做手工的小伙伴们肯定会用到手电钻&#xff0c;那么电池消耗完了&#xff0c;或要换的&#xff0c;或要自己动手做几个备用电源&#xff0c;关键点就是电路保护板的接线。废话不多说&#xff0c;直接上板子看实操。 文章目录 一、线路板图1、输入接线2、输出接线 二、接线方法…

java学习笔记001

java基础 java语言特点 面向对象&#xff0c;强类型&#xff0c;跨平台&#xff0c;解释型 基本概念&#xff08;JVM、JRE、JDK&#xff09; JVM java虚拟机 作用&#xff1a;加载.class文件 JRE Java运行环境 JREJVMJava系统类库 JDK Java开发工具包 JDKJRE编译&a…

英语——方法篇——单词——谐音法+拼音法——50个单词记忆

theatre&#xff0c;剧场&#xff0c;太后th吃eat热re食物&#xff0c;就去剧场了 loud dolphin&#xff0c;做do脸皮厚plh在。。。里 humid&#xff0c;hu湖mi米d的 blender&#xff0c;b爸lend借给er儿。 tragedy&#xff0c;tr土人

笔训【day4】

目录 选择题 1、进制 格式 2、 数组名在&和sizeof后&#xff0c;表数组本身 3、求二维数组某元素地址 ​编辑 ​编辑 4、x x & (x-1) 二进制位1的个数 ​编辑 5、斐波那契递归次数 编程题 1、计算糖果 2、进制转换 选择题 1、进制 格式 十进制转二进制就除…

ARM-day9作业

main.c: #include "uart.h"#include "key_it.h"int main(){char c;char *s;uart4_init(); //串口初始化//中断初始化key_it_config();key3_it_config();//完成GPIO相关初始化all_led_init();//风扇初始化fs_init();//蜂鸣器初始化fmq_init();while(1){…

只有线上出了bug,老板们才知道测试的价值?

有同学说&#xff0c;测试没价值&#xff0c;我们测试团队刚被拆散了。 也有同学说&#xff0c;公司不重视测试&#xff0c;我觉得我们就是测试得太好了。哪天线上出个bug&#xff0c;老板们就知道测试的价值了。 还有人给测试同学规划职业发展路径&#xff0c;就是不做测试&…

C语言 —— 操作符

1. 操作符的分类 算术操作符: - * / % 移位操作符: << >> 位操作符: & | ^ 赋值操作符: - 单目操作符 关系操作符 逻辑操作符 条件操作符 逗号表达式 下标引用、函数调用和结构成员 2. 算术操作符 - * / % 注意 /操作符: 对于整型的除法运算结果依然是整数…

十六、代码校验(2)

本章概要 前置条件 断言&#xff08;Assertions&#xff09;Java 断言语法Guava 断言使用断言进行契约式设计检查指令前置条件后置条件不变性放松 DbC 检查或非常严格的 DbCDbC 单元测试 前置条件 前置条件的概念来自于契约式设计(Design By Contract, DbC), 利用断言机制…

JavaWeb---Servlet

1.Srvlet概述 Servlet是运行在java服务器端的程序&#xff0c;用于接收和响应来着客户端基于HTTP协议的请求 如果想实现Servlet的功能&#xff0c;可以通过实现javax。servlet。Servlet接口或者继承它的实现类 核心方法&#xff1a;service&#xff08;&#xff09;&#xf…

vue七牛云视频直传

完成后样式&#xff1a; 下面的代码是我自己项目里面用到的&#xff0c;一些判断看自己情况去掉&#xff0c;用的是element-ui组件 安装 uuid 库。你可以使用 npm 或 yarn 来完成安装。在终端中执行以下命令&#xff1a; npm install uuidhtml部分 <el-upload class&quo…

海外接单被没收百万收入并处以罚款,承德的这位程序员到底做了什么?

相信在接单圈混的程序员最近都听说了吧&#xff0c;承德的一位程序员因为翻墙接单被没收了105.8万的收入&#xff0c;还被处了10万的罚款&#xff0c;事件一出瞬间登上了热搜并在接单圈广为传播&#xff0c;如果你还没有听说过&#xff0c;也不用担心&#xff0c;现在我就先来给…

webmin远程命令执行漏洞

文章目录 漏洞编号&#xff1a;漏洞描述&#xff1a;影响版本&#xff1a;利用方法&#xff08;利用案例&#xff09;&#xff1a;安装环境漏洞复现 附带文件&#xff1a;加固建议&#xff1a;参考信息&#xff1a;漏洞分类&#xff1a; Webmin 远程命令执行漏洞&#xff08;CV…

python:使用卷积神经网络(CNN)进行回归预测

作者:CSDN @ _养乐多_ 本文详细记录了从Excel或者csv中读取用于训练卷积神经网络(CNN)模型的数据,包括多个自变量和1个因变量数据,以供卷积神经网络模型的训练。随后,我们将测试数据集应用于该CNN模型,进行回归预测和分析。 该代码进一步修改可用于遥感影像回归模型. …

CentOS7 NTP客户端的时间同步详解

需求&#xff1a;在CentOS7下配置NTP客户端时间同步服务 简介&#xff1a; NTP服务是为了时钟同步使用&#xff0c;特别在一些实时性数据库场景中非常重要。 Centos7下默认使用chronyd服务代替过渡ntpd服务&#xff0c;因此经常遇到大部分人还是记住ntpd服务而不去配置chronyd服…

spring6使用启用Log4j2日志框架

文章目录 Log4j2日志概述1. 引入Log4j2依赖2. 加入日志配置文件3. 测试 Log4j2日志概述 在项目开发中&#xff0c;日志十分的重要&#xff0c;不管是记录运行情况还是定位线上问题&#xff0c;都离不开对日志的分析。日志记录了系统行为的时间、地点、状态等相关信息&#xff…

小型企业必备的重要项目管理软件工具推荐!

大多数项目管理软件都包含有助于规划、协作和进度管理的工具。下面列出了在小型团队的项目管理软件中寻找的基本功能。 1、应用内交流 优秀的项目管理软件允许应用程序内通信、向团队成员发送通知以及使用内置聊天功能促进安全协作。 2、仪表盘 仪表板提供个人、团队和部门…

二十、自定义类型:枚举和联合

1 枚举类型 1.1 枚举类型的声明 例&#xff1a; enum Day//星期 {Mon,Tues,Wed,Thur,Fri,Sat,Sun }; enum Sex//性别 {MALE,FEMALE,SECRET }&#xff1b; enum Color//颜⾊ {RED,GREEN,BLUE };以上定义的enum Day&#xff0c;enum Sex&#xff0c;enum Color都是枚举类型。{…

超赞的AI文案生成器!真的什么都能写~

姐妹们&#xff0c;这个AI文案生成器真的太强了&#xff01; 种草笔记、爆款标题、短视频脚本、工作总结、自定义小说生成......只要输入关键词&#xff0c;就能生成一篇专业又优秀的文章&#xff0c;真的太绝了~ 小橙需&#xff1a;写作火火 安卓ios都可用 使用简单&#…

快上车,LLM专列:想要的资源统统给你准备好了

如有转载&#xff0c;请注明出处。欢迎关注微信公众号&#xff1a;低调奋进。​ (嘿嘿&#xff0c;有点标题党了​。最近整理了LLM相关survey、开源数据、开源代码等等资源&#xff0c;后续会不断丰富内容&#xff0c;省略大家找资料浪费时间。闲言少叙&#xff0c;正式发车&a…