Node.js 路由学习笔记

本文将介绍 Node.js 中如何创建和使用路由以及一些实例。

什么是路由?

路由是指根据不同的 URL 请求,将请求分发到相应的处理程序中。在 Node.js 中,我们可以使用路由来处理客户端请求并返回响应。

创建路由

我们可以使用 Node.js 中的 http 模块来创建服务器,并使用相关的路由模块来创建路由。

以下是一个简单的 Node.js 服务器代码,它使用了 urlquerystring 模块来解析请求的 URL 和参数,然后根据请求的路径选择相应的路由进行处理。

javascriptCopy Code
const http = require('http'); const url = require('url'); const querystring = require('querystring'); function start(route, handle) { function onRequest(request, response) { const pathname = url.parse(request.url).pathname; const query = querystring.parse(url.parse(request.url).query); console.log(`Request for ${pathname} received.`); route(handle, pathname, response, query); } http.createServer(onRequest).listen(8888); console.log('Server has started.'); } exports.start = start;

使用路由处理请求

现在,我们已经定义好了服务器和路由,接下来就是将它们组合起来处理请求。

以下是一个简单的路由代码,它通过将路由映射到不同的函数来处理不同的请求:

javascriptCopy Code
function route(handle, pathname, response, query) { console.log(`Routing a request for ${pathname}`); if (typeof handle[pathname] === 'function') { handle[pathname](response, query); } 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;

在这个例子中,请求处理程序被映射到了相应的路由。如果请求的路径没有对应的处理函数,路由会返回一个 404 错误。

路由实例

现在我们来看一个简单的路由实例,它可以根据请求的路径返回不同的响应。

javascriptCopy Code
// app.js const server = require('./server'); const router = require('./router'); const requestHandlers = require('./requestHandlers'); const handle = {}; handle['/'] = requestHandlers.start; handle['/start'] = requestHandlers.start; handle['/upload'] = requestHandlers.upload; server.start(router.route, handle); // router.js function route(handle, pathname, response, query) { console.log(`Routing a request for ${pathname}`); if (typeof handle[pathname] === 'function') { handle[pathname](response, query); } 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; // requestHandlers.js function start(response) { console.log('Request handler "start" was called.'); const body = '<html>' + '<head>' + '<meta http-equiv="Content-Type" content="text/html; ' + 'charset=UTF-8" />' + '</head>' + '<body>' + '<form action="/upload" method="post">' + '<textarea name="text" rows="20" cols="60"></textarea>' + '<br />' + '<input type="submit" value="Submit text" />' + '</form>' + '</body>' + '</html>'; response.writeHead(200, {'Content-Type': 'text/html'}); response.write(body); response.end(); } function upload(response, query) { console.log('Request handler "upload" was called.'); response.writeHead(200, {'Content-Type': 'text/plain'}); response.write(`You've sent the text: ${query.text}`); response.end(); } exports.start = start; exports.upload = upload;

这个例子中,我们定义了三个路由://start/upload。分别对应的请求处理程序为 start()upload()

如果我们访问 http://localhost:8888/start,就会返回一个表单来输入文本,并通过 POST 请求来提交数据;如果我们访问 http://localhost:8888/upload,就会返回提交的文本。如果我们访问其他路径,则会显示 404 Not Found 错误。

结语

至此,我们已经了解了 Node.js 中如何创建和使用路由。实际上,还有很多更高级的路由技巧和工具,例如 Express.js、Koa 等。在实际开发中,可以根据需要选择适合自己的路由方式。