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等,所以大部分情况下原生路由只是做个简单了解。

相关推荐
追逐时光者3 小时前
精选 4 款基于 .NET 开源、功能强大的 Windows 系统优化工具
后端·.net
TF男孩4 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
AAA修煤气灶刘哥5 小时前
别让Redis「歪脖子」!一次搞定数据倾斜与请求倾斜的捉妖记
redis·分布式·后端
AAA修煤气灶刘哥5 小时前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
你的人类朋友5 小时前
什么是API签名?
前端·后端·安全
昵称为空C7 小时前
SpringBoot3 http接口调用新方式RestClient + @HttpExchange像使用Feign一样调用
spring boot·后端
架构师沉默8 小时前
设计多租户 SaaS 系统,如何做到数据隔离 & 资源配额?
java·后端·架构
遂心_8 小时前
JavaScript 函数参数传递机制:一道经典面试题解析
前端·javascript
RoyLin8 小时前
TypeScript设计模式:适配器模式
前端·后端·node.js
该用户已不存在9 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust