Node.js HTTP 服务器路由实现详解
以下是一个简单的 Node.js HTTP 服务器示例,包含路由功能:
var http = require('http');
var url = require('url');
function start(route, handle) {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log('Request for ' + pathname + ' received.');
route(handle, pathname, response, request);
}
http.createServer(onRequest).listen(8888);
console.log('Server has started.');
}
exports.start = start;
在此示例中,我们定义了一个名为 start 的函数,该函数接受两个参数: route 和 handle。这些参数分别表示路由函数和处理程序对象。
在 onRequest 函数中,我们解析了请求的 URL,并将其传递给路由函数,以便确定应该执行哪个处理程序。
接下来,我们可以编写路由功能,例如:
function route(handle, pathname, response, request) {
console.log('Routing request for ' + pathname);
if (typeof handle[pathname] === 'function') {
handle[pathname](response, request);
} else {
console.log('No request handler found for ' + pathname);
response.writeHead(404, {'Content-Type': 'text/plain'});
response.write('404 Not found');
response.end();
}
}
exports.route = route;
在此示例中,我们定义了一个名为 route 的函数,该函数接受四个参数: handle, pathname, response 和 request。 handle 参数是一个对象,其中包含与不同路径相关联的处理程序函数。我们检查 handle 对象中是否有与 pathname 匹配的处理程序函数。如果有,我们调用该函数,并将 response 和 request 对象传递给它。否则,我们发送一个 404 Not Found 响应。
最后,我们可以编写一个处理程序对象,例如:
var handle = {
'/': function(response) {
console.log('Request handler for / called.');
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('Hello World!');
response.end();
},
'/about': function(response) {
console.log('Request handler for /about called.');
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('About page');
response.end();
}
};
exports.handle = handle;
在此示例中,我们定义了一个名为 handle 的对象,其中包含两个处理程序函数,分别用于处理根路径和 about 路径。这些函数都会将 response 对象作为参数,并向客户端发送一些文本响应。
最后,我们可以调用 start 函数并将路由和处理程序对象传递给它,例如:
var server = require('./server');
var router = require('./router');
var handle = require('./handle');
var handle = {
'/': function(response) {
console.log('Request handler for / called.');
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('Hello World!');
response.end();
},
'/about': function(response) {
console.log('Request handler for /about called.');
response.writeHead(200, {'Content-Type': 'text/plain'});
response.write('About page');
response.end();
}
};
server.start(router.route, handle);
在此示例中,我们将 router.route 和 handle 对象传递给 start 函数,以便创建一个可用于处理 HTTP 请求的服务器。
原文地址: https://www.cveoy.top/t/topic/mkZp 著作权归作者所有。请勿转载和采集!