【javascript】初識 NodeJS(三)

來源:互聯網
上載者:User

標籤:load   request   結合   屬性   啟動   系統   else   call   不同的   

上節我們將 http 伺服器(server.js)和請求路由模組(route.js)整合在一起了,當然這還不夠,路由,顧名思義,是指我們要針對不同的 url 有不同的處理方式。

請求處理常式模組(requestHandlers)
function start() {    console.log(‘Request handler "start" was called.‘);}function upload() {    console.log(‘Request handler "upload" was called.‘);}exports.start = start;exports.upload = upload;

下面我們需要將請求處理常式模組和路由模組相結合,修改主檔案 index.js

var server = require(‘./server‘);var route = require(‘./route‘);var requestHandlers = require(‘./requestHandlers‘);var handler = {};handler[‘/‘] = requestHandlers.start;handler[‘/start‘] = requestHandlers.start;handler[‘/upload‘] = requestHandlers.upload;server.start(route.route, handler);

正如所見,將不同的 url 映射到相同的請求處理常式上是很容易的:只要在對象中添加一個鍵為 ‘/‘ 的屬性,對應 requestHandlers.start 即可,這樣我們就可以乾淨簡潔地配置 /start 和 / 的請求都交由 start 這一處理常式處理。在完成了對象的定義後,我們把它作為額外的參數傳遞給伺服器。

var http = require(‘http‘);var url = require(‘url‘);function start(route, handler) {    function onRequest(request, response) {        var pathname = url.parse(request.url).pathname;        console.log(‘Request ‘ + pathname + ‘ received.‘);        route(handler, pathname);        response.writeHead(200, {            ‘Content-type‘: ‘text/plain‘        });        response.write(‘Hello node.js‘);        response.end();    }    http.createServer(onRequest).listen(8888);    console.log(‘server has started.‘);}exports.start = start;

這樣我們就在 start() 函數裡添加了 handler 參數,並且把 handler 對象作為第一個參數傳遞給了 route() 回呼函數。

function route(handler, pathname) {    console.log(‘Route a request for ‘ + pathname);    if (typeof handler[pathname] === ‘function‘) {        handler[pathname]();    } else {        console.log(‘No request handler found for ‘ + pathname);    }}exports.route = route;

這樣,我們就把伺服器、路由和請求處理常式結合在一起了。現在我們啟動應用程式並在瀏覽器中訪問 http://localhost:8888/start,以下日誌可以說明系統調用了正確的請求處理常式:

server has started.Request /start received.Route a request for /startRequest handler "start" was called.Request /favicon.ico received.Route a request for /favicon.icoNo request handler found for /favicon.ico

 

【javascript】初識 NodeJS(三)

聯繫我們

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