Node.js 路由
在 Node.js 中,路由是处理 HTTP 请求的关键部分,它决定了如何根据不同的 URL 和 HTTP 方法(如 GET、POST、PUT、DELETE 等)来分发请求。
路由通常用于构建 Web 应用程序,特别是 RESTful API。
Node.js 本身并没有内置的路由机制,但可以通过中间件库(如 Express)来实现。
路由通常涉及以下几个方面:
- URL 匹配:根据请求的 URL 来匹配路由规则。
- HTTP 方法匹配:根据请求的 HTTP 方法(GET、POST、PUT、DELETE 等)来匹配路由规则。
- 请求处理:一旦匹配到合适的路由规则,就调用相应的处理函数来处理请求。
Node.js 中,我们可以通过 http 模块创建一个简单的路由,如下实例:
实例
const http = require('http');
// 创建服务器并定义路由
const server = http.createServer((req, res) => {
const { url, method } = req;
if (url === '/' && method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Home Page');
} else if (url === '/about' && method === 'GET') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('About Page');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('404 Not Found');
}
});
server.listen(3000, () => {
console.log('Server is running on http://localhost:3000');
});
浏览器访问 http://localhost:3000 显示如下:

浏览器访问 http://localhost:3000/about 显示如下:

如果访问其他 URL 地址,则会直接显示 404 Not Found。
更多 HTTP 请求可以参考:HTTP 教程。
请求参数
一个完整 URL 的 http://localhost:8888/start?foo=bar&hello=world 包含主机、路径和查询字符串。
为

最低0.47元/天 解锁文章
1771

被折叠的 条评论
为什么被折叠?



