node之路由介绍

时间:2023-03-10 06:12:34
node之路由介绍

路由介绍

----路由是指向客户端提供它所发出的请求内容的机制;
----对基于 Web 的客户端 / 服务器端程序而言,客户端在 URL 中指明它想要的内容,具体来说就是路径和查询字符串

下面我看看一下小demo

var http = require('http');

http.createServer(function(req,res){
var path = req.url.replace(/^\/?(?:\?.*)?$/,'').toLowerCase();
console.log(path); switch(path){ case '':
res.writeHead(200,{'Content-Type':'text/plain'});
res.end('HomePage');
break; case '/about':
res.writeHead(200,{'Content-Type':'text/plain'});
res.end('About'); default:
res.writeHead(404,{'Content-Type':'text/plain'});
res.end('Not Found');
break;
}
}).listen(3000,function(){
console.log('run up!');
});

  

运行这段代码,你会发现现在你可以访问首页 (http://localhost: 3000)和关于页面(http://localhost:3000/about)。

所有查询字符串都会被忽略(所以 http://localhost:3000/?foo=bar 也是返回首页),

并且其他所有 URL(http://localhost:3000/foo)返回的都是未找到页面。