node.js是一个基于事件驱动、非阻塞i/o模型的服务器端javascript环境,可以用来构建高效、可扩展地web应用程序。对于node.js的请求处理流程,我们需要分别关注http服务器和路由的实现。
HTTP服务器
Node.js的HTTP服务器模块http模块提供了一个createServer()方法来创建HTTP服务器。每当有一个客户端向服务器发送请求时,该方法都会返回一个Server实例,让我们可以对这个实例进行监听和响应。
创建HTTP服务器
const http = require('http');
http.createServer((request, response) => {
// 请求处理
}).listen(8080);HTTP服务器的request事件
每当有一个用户发送HTTP请求到服务器,服务器就会自动生成一个http.IncomingMessage对象,并触发request事件,我们可以通过该事件来接收和处理HTTP请求。http.IncomingMessage对象也包含了该请求所携带的全部数据,例如请求路径、请求方法、请求头、请求体等。
const http = require('http');
http.createServer((request, response) => {
// request事件
request.on('data', (chunk) => {
console.log(chunk.toString());
});
// 处理请求
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World
');
}).listen(8080);路由
路由是指根据URL请求路径来匹配相应的处理器,从而实现不同URL的访问方式和效果。
路由实现
我们可以通过一个JavaScript对象来存储不同的URL对应的处理器方法,然后在http服务器的request事件中,根据请求路径对该对象进行匹配,从而找到相应的处理器方法进行处理。
const http = require('http');
const urlHandler = {
'/': function(request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World
');
},
'/about': function(request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('About page
');
}
};
http.createServer((request, response) => {
const path = request.url;
if (urlHandler[path]) {
urlHandler[path](request, response);
} else {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.end('404 Not Found
');
}
}).listen(8080);以上是Node.js的请求处理流程的简单实现,通过HTTP服务器和路由模块的协同工作,我们可以建立起一个高效、可扩展的Web服务器,实现各种好玩的Web应用程序。










