我們平時工作中,涉及到后臺開發,路由基本上是我們第一個需要建的,路由還是很重要的。
那么,什么是路由呢,通俗點舉個例子,一個賓館前臺,來了十位客人,前臺會安排十位客人入住,每位客人到達賓館以后,該去哪個房間,都是通過前臺來安排。(別噴我)
在一個域名下,會有很多個可訪問的地址,這就是路由。
我們呢,要為路由提供請求的URL和其他需要的GET及POST參數,隨后路由需要根據這些數據,來決定執行哪些代碼。/
因此,我們要查看HTTP請求,從中提取出來我們需要的URL以及GET/POST參數。
我們需要的這些數據都會包含在request對象中,該對象作為onRequest()回調函數的第一個參數傳遞。但是為了解析這些數據,我們需要額外的Node.js模塊,它們分別是url和querystring模塊。
url.parse(string).query | url.parse(string).pathname | | | | | ------ -------------------http://localhost:8888/start?foo=bar&hello=world --- ----- | | | | querystring.parse(queryString)["foo"] | | querystring.parse(queryString)["hello"]
也可以用querystring模塊來解析post請求體中的參數,下面會有代碼演示。
現在我們寫一段代碼,用來找出瀏覽器請求的URL路徑 之前也寫到如何用node起serve
我們新建一個server.js 代碼如下
// 代碼route()方法為第二個創建的router.js那的方法。我們在這里使用const http = require('http')const url = require('url')function start(route){ function onRequest(request, response) { let pathName = url.parse(request.url).pathname // 通過url獲取到當前訪問路徑 console.log('Request for ' + pathName + 'received.') route(pathName,response) } http.createServer(onRequest).listen(8888) console.log('Server has started')}exports.start = start然后創建router.js
// 通過傳遞過來到pathname,來進行不同的操作,如果是根目錄,打印hello world// 如果是/index 打印 pathname :/index// 如果是其他 打印404function route(pathname,response) { console.log('About to route a request for ' + pathname) response.writeHead(200, {'Content-Type' : 'text/plain'}) if(pathname == '/') { response.write('Hello World') response.end() }else if(pathname == '/index'){ response.write('pathname :/index') response.end() } else { response.write('404') response.end() } }exports.route = route真實環境肯定不會這么寫,這樣寫主要是理解路由的工作原理
接下來我們創建index.js 倒入我們寫好的兩個模塊。
const server = require('./server')const router = require('./router')server.start(router.route)
新聞熱點
疑難解答
圖片精選