如何用Node.js原生http模块实现带参数的GET请求?
使用Node.js原生http模块实现Express风格的动态路由
我已经能用Node.js和Express实现如下请求的处理:
http://localhost:8000/users/1
对应的Express代码如下:
const express = require('express') const app = express() app.get('/users/:userId', (req, res) => { res.send(req.params) })
现在我想改用Node.js原生http模块实现相同功能,现有基础代码如下:
var http = require('http'); //create a server object: let server = http.createServer(function (req, res) { res.write('Hello World!'); //write a response to the client res.end(); //end the response }).listen(8000); //the server object listens on port 8080
请问正确的实现方式是什么?
实现步骤与代码
要实现和Express相同的动态路由功能,需要手动解析请求URL、匹配路由规则并提取参数,具体代码如下:
var http = require('http'); const url = require('url'); // 引入url模块解析请求地址 // 创建服务器 let server = http.createServer(function (req, res) { // 解析请求的URL,获取路径部分 const parsedUrl = url.parse(req.url); const pathname = parsedUrl.pathname; // 定义路由规则:匹配/users/xxx格式的路径 const userRouteRegex = /^\/users\/(\d+)$/; const match = pathname.match(userRouteRegex); // 检查是否匹配目标路由,且请求方法为GET if (req.method === 'GET' && match) { // 提取userId参数(正则捕获组的第一个结果) const userId = match[1]; // 设置响应头为JSON格式 res.setHeader('Content-Type', 'application/json'); // 返回参数对象的JSON字符串 res.end(JSON.stringify({ userId })); } else { // 不匹配时返回404 res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('404 Not Found'); } }).listen(8000); // 监听8000端口(修正原代码注释的端口不一致问题)
代码说明:
- 引入
url模块:用于解析请求的URL路径,分离出pathname部分(比如/users/1)。 - 正则匹配路由:用
/^\/users\/(\d+)$/匹配以/users/开头、后面跟数字的路径,(\d+)是捕获组,用来提取userId。 - 检查请求方法:确保是GET请求,和Express的
app.get逻辑对应。 - 响应处理:匹配成功时设置JSON响应头,返回包含userId的JSON对象;不匹配时返回404状态码和提示。
测试时访问http://localhost:8000/users/1,会得到{"userId":"1"}的响应,和Express版本的效果完全一致。
内容的提问来源于stack exchange,提问作者Learner
相关产品推荐
相关产品推荐

