2016-02-27 102 views
0

我刚刚开始阅读使用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'); 

homeabout,并404每个HTML文件中都有自己的<img>标签,所以我想的图像会在用户请求一个URL自动呈现。我们如何在switch中需要额外的案例来处理图像?例如,如果我输入http://localhost:8080/about,它将记录2,然后4。为什么about的情况也称为'/img/logo.jpeg'

回答

1

这是因为图像是由浏览器分别从html,js文件,css文件请求的。

每个静态资源都由浏览器在单独的http请求中获取。如果一个html页面需要5个javascript文件,3个css文件,4个图像,浏览器将发出5 + 3 + 4 + 1 = 13个请求。

+0

有趣,谢谢你的简单回答! – MarksCode

1

'/about'案例日志2并呈现静态文件'/public/about.html'。我敢打赌,'/public/about.html'页面包含一个图像标记,如<img src="/public/img/logo.jpeg">。这将打击服务器的网址'/public/img/logo.jpeg',并登录4.

因此,你的case语句正确地打破;这只是您可能向服务器发出两个请求:一个用于关于页面,另一个用于标识图像。

+0

这让人很有道理,谢谢你! – MarksCode

1

我也读过这本书。你提到的代码在第2章中,更多的是一种笨拙的路由方式。在接下来的章节中,作者继续讨论Express如何使路由变得容易。

要回答你的问题,你不需要switch语句中的路由或API来处理图像。只要路径位于客户端返回或构建的HTML中,图像就会自动下载。

+0

是的,我正在写第3章,我只是想了解基本知识,然后才转到 – MarksCode