nodejs之請求路由概述

來源:互聯網
上載者:User

通常來說對於不同的URL請求,伺服器應該有不同的反應。我們要為路由提供請求的URL和其他需要的GET及POST參數,隨後路由需要根據這些資料來執行相應的代碼。我們需要的所有資料都會包含在request對象中,該對象作為onRequest()回呼函數的第一個參數傳遞。為瞭解析這些資料,需要調用額外的模組,分別是url和querystring模組。
 
URL:This
 module has utilities for URL resolution and parsing. Call require('url') to
 use it.
 
Parsed URL objects have some or all of the following fields, depending on whether or not they exist in the URL string. Any parts that are not in the URL string will not be in the parsed object. Examples are shown for the URL
 
'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
 
href: The full URL that was originally parsed. Both the protocol and host are lowercased.
Example: 'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'
 
protocol: The request protocol, lowercased.
Example: 'http:'
 
host: The full lowercased host portion of the URL, including port information.
Example: 'host.com:8080'
 
auth: The authentication information portion of a URL.
Example: 'user:pass'
 
hostname: Just the lowercased hostname portion of the host.
Example: 'host.com'
 
port: The port number portion of the host.
Example: '8080'
 
pathname: The path section of the URL, that comes after the host and before the query, including the initial slash if present.
Example: '/p/a/t/h'
 
search: The 'query string' portion of the URL, including the leading question mark.
Example: '?query=string'
 
path: Concatenation of pathname and search.
Example: '/p/a/t/h?query=string'
 
query: Either the 'params' portion of the query string, or a querystring-parsed object.
Example: 'query=string' or {'query':'string'}
 
hash: The 'fragment' portion of the URL including the pound-sign.
Example: '#hash'
 
我們將使用依賴注入的方式較鬆散地添加路由模組。作為路由目標的函數稱為請求處理常式,請求處理函數的實現需要建立一個叫做requestHandlers的模組,當然也可以命名為其他。並對於每一個請求處理常式,添加一個佔位用函數,隨後將這些函數作為模組的方法匯出,這樣就可以將請求處理常式和路由模組串連起來,讓路由有路可循。
 
特別指出的是,這裡需要將一系列請求處理常式通過一個對象來傳遞,並且需要使用松耦合的方式將這個對象注入到route()函數中。

我們可以用從關聯陣列中擷取元素一樣的方式從傳遞的對象中擷取請求處理函數,因此就有了簡潔流暢的形如handle[pathname]();的運算式。代碼如下所示:

var handle = {}handle["/"] = requestHandlers.start;handle["/start"] = requestHandlers.start;handle["/upload"] = requestHandlers.upload;

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.