JavaScript Node.js路由
什么是路由?
在 Web 开发中,路由(Routing) 是指确定应用程序如何响应客户端对特定端点的请求,这个端点是由 URI(或路径)和特定的 HTTP 请求方法(GET、POST 等)组成的。
简单来说,路由就是将用户请求映射到相应处理函数的过程,它决定了用户访问不同 URL 路径时,服务器应该返回什么内容。
Node.js 原生路由
在 Node.js 中,可以使用内置的 http
模块来创建服务器并处理不同路由。下面是一个简单的例子:
const http = require('http');
const url = require('url');
const server = http.createServer((req, res) => {
// 解析请求的 URL
const parsedUrl = url.parse(req.url, true);
const path = parsedUrl.pathname;
const trimmedPath = path.replace(/^\/+|\/+$/g, '');
// 设置响应头
res.setHeader('Content-Type', 'text/plain');
// 路由逻辑
if (trimmedPath === '') {
res.writeHead(200);
res.end('这是首页\n');
} else if (trimmedPath === 'about') {
res.writeHead(200);
res.end('这是关于页面\n');
} else if (trimmedPath === 'api/users') {
res.setHeader('Content-Type', 'application/json');
res.writeHead(200);
res.end(JSON.stringify({ users: ['Alice', 'Bob', 'Charlie'] }));
} else {
res.writeHead(404);
res.end('页面未找到\n');
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`服务器运行在 http://localhost:${PORT}`);
});
上面的代码实现了一个简单的路由系统:
/
(空路径) - 返回首页内容/about
- 返回关于页内容/api/users
- 返回用户列表 JSON- 其他路径 - 返回 404 错误
备注
原生 Node.js 路由实现相对繁琐,需要手动解析 URL,并使用条件语句处理不同路由。这种方式适合简单应用,但在复杂应用中会导致代码难以维护。