node函數 node路由

node函數

js中一個函數能夠做爲另外一個函數的參數,即先定義一個函數,而後傳遞html

匿名函數

這個學過,過node

node路由

要爲路由提供請求的url,和其餘須要的get的post請求。
隨後,路由會根據須要進行執行響應的代碼。
所以,須要根據http請求,從中提取中須要的url和get和post參數segmentfault

兩個模塊,url和qureystring模塊

http://localhost:8888/start?foo=bar&hello=word

這個url中
url.parse(string).pathname   start
url.parse(string).query    參數部分即問號後面的內容

querystring.parse(queryString)['foo']    bar內容
querystring.parse(queryString)['hello']  word內容

這是說明瀏覽器

提取url

var http = require('http');
var url = require('url');

(function start() {    // 建立一個命名空間
    function onRequest(request, response) {
        var pathname = url.parse(request.url).pathname;    // 提取出來url的內容
        console.log(pathname);
        response.writeHead(200, {'Content-Type': 'text/plain'});
        response.write('hello word');
        response.end();
    };

    http.createServer(onRequest).listen(1937);
}());

訪問鏈接 http://127.0.0.1:1937/hello%20word.html
http://127.0.0.1:1937/hello%20word
返回消息緩存

PS C:\Users\mingm\Desktop\test> node main.js
/hello%20word
/favicon.ico
/hello%20word.html
/favicon.ico

兩個請求,一個是hello word的請求,因爲url不支持空格,因此用%20進行替代,node返回客戶端請求的是hello word
favicon.ico是瀏覽器默認的一個請求,若沒有圖標文件的緩存都會對服務器請求一個圖標文件服務器

編寫一個路由

PS C:\Users\mingm\Desktop\test> node index.js
Server has started.
hello word!
hello word!

文件結構函數

- test
    router.js
    server.js
    index.js

文件內容post

// router.js
function route(pathname) {
    console.log("hello word!");
};

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;

        route(pathname);    // 使用route的js模塊(已經在router.js文件導出)傳入的參數的值爲pathname
        
        response.writeHead(200, {'Content-Type': 'text/html'});
        response.write('<head><meta charset="utf-8"></head>');
        response.write('Hello word! hello word!');
        response.end();
    };

    http.createServer(onRequest).listen(1937);
      console.log("Server has started.");
};

exports.start = start;



// index.js
var server = require('./server');
var router = require('./router');

server.start(router.route);

訪問結果ui

http://127.0.0.1:1937/
Hello word! hello word!

我的博客

www.iming.infourl

相關文章
相關標籤/搜索