node.js-------使用路由模組

來源:互聯網
上載者:User

標籤:style   blog   http   color   io   os   使用   java   ar   

 

路由需要的資訊,包括URL 及GET 或 POST參數。路由根據這些參數執行相應的js處理常式,因此,需要在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(string)["foo"]

                querystring(string)["hello"]

 

當然可以用querystring模組來解釋POST請求體中的參數。

可以通過不同的請求的URL路徑來映射到不同的處理常式上面,路由就是做這一個工作。

例如來自:/start和/upload的請求可以使用不同的程式來處理。

 

下面是一個例子:

---index.js

---server.js

---route.js

 

編寫一個路由,route.js

function route(pathname){console.log("About to route a request for "  +  pathname);}exports.route = route;

 編寫處理請求的頁面,server.js

var http = require("http");var url = require(‘url‘);function start(route){function onRequest(request, response){var pathname = url.parse(request.url).pathname;console.log("Request for " + pathname + "received");route(pathname);//在這裡可以對不同的路徑進行處理//if(pathname =="...") response.writeHead不同的資訊之類response.writeHead(200, {"Content-Type" : "text/plain"});response.write("Hello World");response.end();}http.createServer(onRequest).listen(3000);console.log("Server has started.");}exports.start = start;

編寫開機檔案,index.js

var server = require("./server");var router = require("./router");server.start(router.route);

在用戶端啟動應用,伺服器啟動,開始監聽3000連接埠:

node index.js

在瀏覽器端輸入一個請求URL:

http://127.0.0.1:3000/

看到相應的用戶端輸出:

 瀏覽器顯示:

 

node.js-------使用路由模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.