Page 97 - Node.js开发指南
P. 97

90  第 5 章  使用 Node.js 进行 Web 开发


             完成了许多透明的工作,现在就让我们来解释一下它的工作机制,以帮助理解网站的整
             体架构。
                 访问 http://localhost:3000,浏览器会向服务器发送以下请求:

                 GET / HTTP/1.1
                 Host: localhost:3000
                 Connection: keep-alive
                 Cache-Control: max-age=0
                 User-Agent: Mozilla/5.0 AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.142
                   Safari/535.19
                 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
                 Accept-Encoding: gzip,deflate,sdch
                 Accept-Language: zh;q=0.8,en-US;q=0.6,en;q=0.4
                 Accept-Charset: UTF-8,*;q=0.5
                 其中第一行是请求的方法、路径和 HTTP 协议版本,后面若干行是 HTTP 请求头。app 会
             解析请求的路径,调用相应的逻辑。app.js 中有一行内容是 app.get('/', routes.index),
             它的作用是规定路径为“/”的 GET 请求由 routes.index 函数处理。routes.index 通

             过 res.render('index', { title: 'Express' }) 调用视图模板 index,传递 title
             变量。最终视图模板生成 HTML 页面,返回给浏览器,返回的内容是:


                 HTTP/1.1 200 OK
                 X-Powered-By: Express
                 Content-Type: text/html; charset=utf-8
                 Content-Length: 202
                 Connection: keep-alive

                 <!DOCTYPE html>
                 <html>
                   <head>
                     <title>Express</title>
                     <link rel='stylesheet' href='/stylesheets/style.css' />
                   </head>
                   <body>
                     <h1>Express</h1>
                 <p>Welcome to Express</p>
                   </body>
                 </html>
                 浏览器在接收到内容以后,经过分析发现要获取 /stylesheets/style.css,因此会再次向服
             务器发起请求。app.js  中并没有一个路由规则指派到 /stylesheets/style.css,但  app  通过
             app.use(express.static(__dirname + '/public')) 配置了静态文件服务器,因此
             /stylesheets/style.css 会定向到 app.js 所在目录的子目录中的文件 public/stylesheets/style.css,
             向客户端返回以下信息:
   92   93   94   95   96   97   98   99   100   101   102