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

最后

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

相关推荐
高频因子挖掘机31 分钟前
实时行情为什么不应该逐只股票请求?批量查询与标的池管理实践
后端·github·api
程序猿DD6 小时前
OctaFuse Gateway 2.15.0:MCP 聚合、向量 Embeddings 与官方目录同步
后端·agent
鬼手点金7 小时前
nanoGPT/nanochat 能做出 DeepSeek/Qwen 这样的大模型吗?
服务器·前端·javascript·bug·openclaw
软件技术NINI8 小时前
美妆商城html+Css+js 4页
javascript·css·html
蛋蛋的就会顺顺的8 小时前
hot100 p0——栈,贪心算法,动态规划
java·前端·javascript·算法·leetcode·力扣
余槐i8 小时前
PostgreSQL 函数索引报错 must be immutable:3种绕法与代价
数据库·后端·sql·postgresql·性能优化
需要8269 小时前
Spring Bean 生命周期:从实例化到销毁的完整钩子
java·后端·spring
码艺-Alimjan9 小时前
Tauri 源码备份 · 打包 & 解压 总结,源码收集之路
前端·javascript·vue.js
凤山老林10 小时前
Spring Boot 接入国密 SM2/SM3/SM4 的一些实践记录
spring boot·后端·python
伯恩bourne11 小时前
Spring Boot Bean 注册的两种方式:@Component 家族 vs @Configuration + @Bean
java·spring boot·后端