Node.js路由浅析

什么是路由?

路由是指根据请求的URL和HTTP方法(如GET、POST等)来确定如何处理请求的过程。简单来说,路由就是将用户的请求"指引"到相应的处理函数。

Node.js中的路由

路由通常涉及以下几个方面:

  • URL 匹配:根据请求的 URL 来匹配路由规则。
  • HTTP 方法匹配:根据请求的 HTTP 方法(GET、POST、PUT、DELETE 等)来匹配路由规则。
  • 请求处理:一旦匹配到合适的路由规则,就调用相应的处理函数来处理请求

下图是官网提供的完整URL各个部分的解析

在Node.js中,我们可以使用内置的http模块来实现基本的路由功能。下面是一个简单的例子:

javascript 复制代码
const http = require('http');
const URL = require('url');

const server = http.createServer((req, res) => {
    let newUrl = new URL.URL(req.url, 'http://localhost:3000');// 使用Node.js新版的WHATWG方式把请求的路由url封装成url对象
    console.log(newUrl);
    // newUrl 对象输出,pathname就是路由
    // URL {
    //     href: 'http://localhost:3000/about',
    //     origin: 'http://localhost:3000',
    //     protocol: 'http:',
    //     username: '',
    //     password: '',
    //     host: 'localhost:3000',
    //     hostname: 'localhost',
    //     port: '3000',
    //     pathname: '/about',
    //     search: '',
    //     searchParams: URLSearchParams {},
    //     hash: ''
    //   }
    const reqUrl = req.url;
    
    const method = reqUrl.method;

    if (reqUrl === '/' && method === 'GET') {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.end('Welcome to the homepage!');
    } else if (reqUrl === '/about' && method === 'GET') {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/plain');
        res.end('This is the about page.');
    } else {
        res.statusCode = 404;
        res.setHeader('Content-Type', 'text/plain');
        res.end('404 Not Found');
    }
});

server.listen(3000, () => {
    console.log('Server running at http://localhost:3000/');
});

访问 http://localhost:3000http://localhost:3000/about,你将分别看到如下的界面。访问其他路径(例如:http://localhost:3000/page),则会显示 "404 Not Found"。

最后

一般现在web开发都是借助第三方库来实现,比如Express,Koa等,所以大部分情况下原生路由只是做个简单了解。

相关推荐
超浪的晨27 分钟前
Java UDP 通信详解:从基础到实战,彻底掌握无连接网络编程
java·开发语言·后端·学习·个人开发
AntBlack35 分钟前
从小不学好 ,影刀 + ddddocr 实现图片验证码认证自动化
后端·python·计算机视觉
hui函数1 小时前
掌握JavaScript函数封装与作用域
前端·javascript
Pomelo_刘金1 小时前
Clean Architecture 整洁架构:借一只闹钟讲明白「整洁架构」的来龙去脉
后端·架构·rust
双力臂4041 小时前
Spring Boot 单元测试进阶:JUnit5 + Mock测试与切片测试实战及覆盖率报告生成
java·spring boot·后端·单元测试
Carlos_sam2 小时前
Opnelayers:ol-wind之Field 类属性和方法详解
前端·javascript
小毛驴8502 小时前
创建 Vue 项目的 4 种主流方式
前端·javascript·vue.js
bingbingyihao2 小时前
Node.js 模拟 Linux 环境
linux·node.js
midsummer_woo3 小时前
基于spring boot的医院挂号就诊系统(源码+论文)
java·spring boot·后端
你这个年龄怎么睡得着的3 小时前
Babel AST 魔法:Vite 插件如何让你的 try...catch 不再“裸奔”?
前端·javascript·vite