02. 路由匹配
于2022-10-31 11:15:55发布
69
在上一章节中,我们在浏览器的地址栏上,不管输入什么地址。只要是http://localhost:8080/a.html 或者 http://localhost:8080/1.jpg。 都能返回 “hello world”。为了解决这个问题,我们来修改下上一章的代码。
const http = require('http');
var server = http.createServer(function(req, res){
// 匹配 START
switch(req.url) {
case '/1.html':
res.write('1111');
break;
case '/2.html':
res.write('2222');
break;
default :
res.write('404');
break;
}
// 匹配 END
res.end();
});
server.listen(8080);
console.log('server is run ....');
在浏览器上输入http://localhost:8080/1.html 返回1111
在浏览器上输入http://localhost:8080/2.html 返回2222
在浏览器上输入http://localhost:8080/xxx.html 返回404 (xxx是任意字符串)
分析
request中的url属性,能获取到http://localhost:8080后面的内容。比如地址栏上是http://localhost:8080/1.html, 则request.url返回/1.html