当前位置: 首页 > news >正文

【Node.js】路由

基础使用

写法一:

// 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')breakdefault: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 falseif (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

相关文章:

【Node.js】路由

基础使用 写法一&#xff1a; // 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…...

matlab 2ask 4ask 信号调制

1 matlab 2ask close all clear all clcL =1000;Rb=2822400;%码元速率 Fs =Rb*8; Fc=Rb*30;%载波频率 Ld =L*Fs/Rb;%产生载波信号 t =0:1/Fs:L/Rb;carrier&...

Python利用jieba分词提取字符串中的省市区(字符串无规则)

目录 背景库&#xff08;jieba&#xff09;代码拓展结尾 背景 今天的需求就是在一串字符串中提取包含&#xff0c;省、市、区&#xff0c;该字符串不是一个正常的地址;,如下字符串 "安徽省、浙江省、江苏省、上海市,冷运标快首重1kg价格xx元,1.01kg(含)-5kg(不含)续重价…...

MuLogin防关联浏览器帮您一键实现Facebook账号多开

导言&#xff1a; 在当今数字化时代&#xff0c;社交媒体应用程序的普及程度越来越高。Facebook作为全球最大的社交媒体平台之一&#xff0c;拥有数十亿的用户。然而&#xff0c;对于一些用户来说&#xff0c;只拥有一个Facebook账号可能无法满足他们的需求。有时&#xff0c;…...

【C语言】每日一题(半月斩)——day4

目录 选择题 1、设变量已正确定义&#xff0c;以下不能统计出一行中输入字符个数&#xff08;不包含回车符&#xff09;的程序段是&#xff08; &#xff09; 2、运行以下程序后&#xff0c;如果从键盘上输入 65 14<回车> &#xff0c;则输出结果为&#xff08; &…...

Are you sure you want to continue connecting (yes/no) 每次ssh进

Lunix scp等命令不需要输入yes确认方法_scp不需要确认-CSDN博客 方法一&#xff1a;连接时加入StrictHostKeyCheckingno ssh -o StrictHostKeyCheckingno root192.168.1.100 方法二&#xff1a;修改/etc/ssh/ssh_config配置文件&#xff0c;添加&#xff1a; StrictHostKeyC…...

网络与信息系统安全设计规范

1、总则 1.1、目的 为规范XXXXX单位信息系统安全设计过程&#xff0c;确保整个信息安全管理体系在信息安全设计阶段符合国家相关标准和要求&#xff0c;特制订本规范。 1.2、范围 本规范适用于XXXXX单位在信息安全设计阶段的要求和规范管理。 1.3、职责 网络安全与信息化…...

在Linux怎么用vim实现把一个文件里面的文本复制到另一个文件里面

2023年10月9日&#xff0c;周一下午 我昨天遇到了这个问题&#xff0c;但在网上没找到图文并茂的博客&#xff0c;于是我自己摸索出解决办法后&#xff0c;决定写一篇图文并茂的博客。 情景 假设现在我要用vim把file_transfer.cpp的内容复制到file_transfer.hpp里面 第一步 …...

CCAK—云审计知识证书学习

目录 一、CCAK云审计知识证书概述 二、云治理概述 三、云信任 四、构建云合规计划 <...

3.springcloudalibaba gateway项目搭建

文章目录 前言一、搭建gateway项目1.1 pom配置1.2 新增配置如下 二、新增server服务2.1 pom配置2.2新增测试接口如下 三、测试验证3.1 分别启动两个服务&#xff0c;查看nacos是否注册成功3.2 测试 总结 前言 前面已经完成了springcloudalibaba项目搭建&#xff0c;接下来搭建…...

Debezium日常分享系列之:Debezium 2.3.0.Final发布

Debezium日常分享系列之&#xff1a;Debezium 2.3.0.Final发布 一、重大改变二、PostgreSQL / MySQL 安全连接更改三、JDBC 存储编码更改四、新功能和改进五、Kubernetes 的 Debezium Server Operator六、新的通知子系统七、新的可扩展信号子系统八、JMX 信号和通知集成九、新的…...

js为什么是单线程?

基础 js为什么是单线程&#xff1f; 多线程问题 类比操作系统&#xff0c;多线程问题有&#xff1a; 单一资源多线程抢占&#xff0c;引起死锁问题&#xff1b;线程间同步数据问题&#xff1b; 总结 为了简单&#xff1a; 更简单的dom渲染。js可以操控dom&#xff0c;而一…...

centos安装redis教程

centos安装redis教程 安装的版本为centos7.9下的redis3.2.100版本 1.下载地址 Index of /releases/ 使用xftp将redis传上去。 2.解压 tar -zxvf 文件名.tar.gz 3.安装 首先&#xff0c;确保系统已经安装了GCC编译器和make工具。可以使用以下命令进行安装&#xff1a; sudo y…...

把短信验证码储存在Redis

校验短信验证码 接着上一篇博客https://blog.csdn.net/qq_42981638/article/details/94656441&#xff0c;成功实现可以发送短信验证码之后&#xff0c;一般可以把验证码存放在redis中&#xff0c;并且设置存放时间&#xff0c;一般短信验证码都是1分钟或者90s过期&#xff0c;…...

【已编译资料】基于正点原子alpha开发板的第三篇系统移植

系统移植的三大步骤如下&#xff1a; 系统uboot移植系统linux移植系统rootfs制作 一言难尽&#xff0c;踩了不少坑&#xff0c;当时只是想学习驱动开发&#xff0c;发现必须要将第三篇系统移植弄好才可以学习后面驱动&#xff0c;现将移植好的文件分享出来&#xff1a; 仓库&…...

地下城堡3魂之诗食谱,地下城堡3菜谱37种

地下城堡3魂之诗食谱大全&#xff0c;让你解锁制作各种美食的方法&#xff01;不同的食材搭配不同的配方制作&#xff0c;食物效果和失效也迥异。但有时候我们可能会不知道如何制作这些食物&#xff0c;下面为您介绍地下城堡3菜谱37种。 关注【娱乐天梯】&#xff0c;获取内部福…...

HDMI 基于 4 层 PCB 的布线指南

HDMI 基于 4 层 PCB 的布线指南 简介 HDMI 规范文件里面规定其差分线阻抗要求控制在 100Ω 15%&#xff0c;其中 Rev.1.3a 里面规定相对放宽了一些&#xff0c;容忍阻抗失控在 100Ω 25%范围内&#xff0c;不要超过 250ps。 通常&#xff0c;在 PCB 设计时&#xff0c;注意控…...

理解Go中的布尔逻辑

布尔数据类型(bool)可以是两个值之一&#xff0c;true或false。布尔值在编程中用于比较和控制程序流程。 布尔值表示与数学逻辑分支相关的真值&#xff0c;它指示计算机科学中的算法。布尔(Boolean)一词以数学家乔治布尔(George Boole)命名&#xff0c;总是以大写字母B开头。 …...

rv1126-rknpu-v1.7.3添加opencv库

rv1126所使用的rknn sdk里默认是不带opencv库的&#xff0c;官方所用的例程里也没有使用opencv&#xff0c;但是这样在进行图像处理的时候有点麻烦了&#xff0c;这里有两种办法: 一是先用python将所需要的图片处理好后在转化为bin格式文件&#xff0c;在使用c或c进行读取&…...

【Redis】Redis持久化深度解析

原创不易&#xff0c;注重版权。转载请注明原作者和原文链接 文章目录 Redis持久化介绍RDB原理Fork函数与写时复制关于写时复制的思考 RDB相关配置 AOF原理AOF持久化配置AOF文件解读AOF文件修复AOF重写AOF缓冲区与AOF重写缓存区AOF缓冲区可以替代AOF重写缓冲区吗AOF相关配置写后…...

c/c++--字节对齐(byte alignment)

1. 默认字节对齐 在所有结构体成员的字节长度都没有超出操作系统基本字节单位(32位操作系统是4,64位操作系统是8)的情况下 按照结构体中字节最大的变量长度来对齐&#xff1b;若结构体中某个变量字节超出操作系统基本字节单位 那么就按照系统字节单位来对齐。 注意&#xff1…...

算法进阶——字符串的排列

题目 输入一个长度为 n 字符串&#xff0c;打印出该字符串中字符的所有排列&#xff0c;你可以以任意顺序返回这个字符串数组。 例如输入字符串ABC,则输出由字符A,B,C所能排列出来的所有字符串ABC,ACB,BAC,BCA,CBA和CAB。 数据范围&#xff1a;n<10 要求&#xff1a;空间复…...

js中 slice 用法用法全解析

slice 工作原理 在深入研究一些更高级的用法之前&#xff0c;让我们看一下 slice 方法的基础知识。如MDN文档&#xff0c; slice 是数组上的一个方法&#xff0c;它最多有两个参数: arr.slice([begin[, end]]) begin 从该索引处开始提取原数组中的元素,如果该参数为负数&am…...

Typora安装教程

Typora 安装教程 安装 官网最新版 自行官网下载 社区版&#xff08;老版本&#xff0c;附带激活码&#xff09; 链接: https://pan.baidu.com/s/1t_3o3Xi7x09_8G1jpQYIvg?pwdmeyf 提取码: meyf 复制这段内容后打开百度网盘手机App&#xff0c;操作更方便哦 将百度云盘下…...

Pytorch中张量的维度扩张与广播操作示例

广播操作允许你对不同形状的张量执行逐元素操作&#xff0c;而无需显式循环。 一个关于分子坐标离散格点化的实战例子&#xff1a; def cdists(mols, grid):Calculates the pairwise Euclidean distances between a set of molecules and a listof positions on a grid (uses…...

身份证号码,格式校验:@IdCard(自定义注解)

目标 自定义一个用于校验 身份证号码 格式的注解IdCard&#xff0c;能够和现有的 Validation 兼容&#xff0c;使用方式和其他校验注解保持一致&#xff08;使用 Valid 注解接口参数&#xff09;。 校验逻辑 有效格式 符合国家标准。 公民身份号码按照GB11643&#xff0d;…...

【Java】instanceof 关键字

instanceof 通过返回一个布尔值来指出&#xff0c;某个对象是否是某个特定类或者是该特定类的子类的一个实例。 如果 object 是class 的一个实例&#xff0c;则 instanceof 运算符返回 true&#xff0c;如果 object 不是指定类的一个实例&#xff0c;或者object 是null, 则返回…...

Android 13.0 recovery出厂时正在清理字体大小的修改

1.前言 在13.0的系统rom定制化开发中,在系统中recovery模块也是系统中比较重要的模块,比如恢复出厂设置,recovery ota升级,清理缓存等等, 在一些1080p的设备,但是density只是240这样的设备,会在恢复出厂设置的时候,显示的字体有点小,产品要求需要将正在清理的字体调大…...

京东商品数据:8月京东环境电器行业数据分析

8月份&#xff0c;环境电器大盘市场整体下滑。鲸参谋数据显示&#xff0c;8月京东平台环境电器的大盘将近570万&#xff0c;环比下滑约29%&#xff0c;同比下滑约10%&#xff1b;销售额为25亿&#xff0c;环比下滑约23%&#xff0c;同比下滑约8%。 *数据源于鲸参谋-行业趋势分析…...

elasticsearch(ES)分布式搜索引擎04——(数据聚合,自动补全,数据同步,ES集群)

目录 1.数据聚合1.1.聚合的种类1.2.DSL实现聚合1.2.1.Bucket聚合语法1.2.2.聚合结果排序1.2.3.限定聚合范围1.2.4.Metric聚合语法1.2.5.小结 1.3.RestAPI实现聚合1.3.1.API语法1.3.2.业务需求1.3.3.业务实现 2.自动补全2.1.拼音分词器2.2.自定义分词器2.3.自动补全查询2.4.实现…...