我刚刚开始阅读使用Node和Express的Web开发,并且遇到了本书中未回答的问题。他们给出了一个基本的布局,允许服务器请求home
,和/404
。每个人都有自己的HTML文件,其中有一张图片。服务器路径的流
这里是他们给的代码:
var http = require('http');
var fs = require('fs');
function serveStaticFile(res, path, contentType, responseCode){
if(!responseCode) responseCode = 200;
fs.readFile(__dirname + path, function(err, data){
if(err){
res.writeHead(500, {'Content-Type':'text/plain'});
res.end('500 - Internal Error');
} else {
res.writeHead(responseCode, {'Content-Type':contentType});
res.end(data);
}
});
}
http.createServer(function(req, res){
//normalize url by removing querystring, optional
//trailing slash, and making it lowercase
var path = req.url.replace(/\/?(?:\?.*)?$/,'').toLowerCase();
switch(path){
case '':
console.log('1');
serveStaticFile(res, '/public/home.html', 'text/html');
break;
case '/about':
console.log('2');
serveStaticFile(res, '/public/about.html', 'text/html');
break;
case '/img/error.jpeg':
console.log('3');
serveStaticFile(res, '/public/img/error.jpeg', 'image/jpeg');
break;
case '/img/logo.jpeg':
console.log('4');
serveStaticFile(res, '/public/img/logo.jpeg', 'image/jpeg');
break;
default:
console.log('5');
serveStaticFile(res, '/public/404.html', 'text/html');
break;
}
}).listen(8080);
console.log('Server started on localhost:8080');
为home
,about
,并404
每个HTML文件中都有自己的<img>
标签,所以我想的图像会在用户请求一个URL自动呈现。我们如何在switch
中需要额外的案例来处理图像?例如,如果我输入http://localhost:8080/about
,它将记录2
,然后4
。为什么about
的情况也称为'/img/logo.jpeg'
?
有趣,谢谢你的简单回答! – MarksCode