[Node.js基礎(chǔ)]學(xué)習(xí)⑧--http

HTTP協(xié)議

HTTP服務(wù)器

'use strict';

// 導(dǎo)入http模塊:
var http = require('http');

// 創(chuàng)建http server暇务,并傳入回調(diào)函數(shù):
var server = http.createServer(function (request, response) {
    // 回調(diào)函數(shù)接收request和response對(duì)象,
    // 獲得HTTP請(qǐng)求的method和url:
    console.log(request.method + ': ' + request.url);
    // 將HTTP響應(yīng)200寫入response, 同時(shí)設(shè)置Content-Type: text/html:
    response.writeHead(200, {'Content-Type': 'text/html'});
    // 將HTTP響應(yīng)的HTML內(nèi)容寫入response:
    response.end('<h1>Hello world!</h1>');
});

// 讓服務(wù)器監(jiān)聽8080端口:
server.listen(8080);

console.log('Server is running at http://127.0.0.1:8080/');

在命令提示符下運(yùn)行該程序

$ node hello.js 
Server is running at http://127.0.0.1:8080/

不要關(guān)閉命令提示符,直接打開瀏覽器輸入http://localhost:8080,即可看到服務(wù)器響應(yīng)的內(nèi)容:

Paste_Image.png
GET: /
GET: /favicon.ico

文件服務(wù)器

資源下載地址
https://github.com/michaelliao/learn-javascript

Paste_Image.png

將一個(gè)字符串解析為一個(gè)Url對(duì)象:

'use strict';

var url = require('url');

console.log(url.parse('http://user:pass@host.com:8080/path/to/file?query=string#hash'));

結(jié)果

Url {
  protocol: 'http:',
  slashes: true,
  auth: 'user:pass',
  host: 'host.com:8080',
  port: '8080',
  hostname: 'host.com',
  hash: '#hash',
  search: '?query=string',
  query: 'query=string',
  pathname: '/path/to/file',
  path: '/path/to/file?query=string',
  href: 'http://user:pass@host.com:8080/path/to/file?query=string#hash' }

完整代碼

urls.js

'use strict';

var url = require('url');

// parse url:
console.log(url.parse('http://user:pass@host.com:8080/path/to/file?query=string#hash'));

// parse incomplete url:
console.log(url.parse('/static/js/jquery.js?name=Hello%20world'));

// construct a url:
console.log(url.format({
    protocol: 'http',
    hostname: 'localhost',
    pathname: '/static/js',
    query: {
        name: 'Nodejs',
        version: 'v 1.0'
    }
}));
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '?name=Hello%20world',
  query: 'name=Hello%20world',
  pathname: '/static/js/jquery.js',
  path: '/static/js/jquery.js?name=Hello%20world',
  href: '/static/js/jquery.js?name=Hello%20world' }
http://localhost/static/js?name=Nodejs&version=v%201.0

文件服務(wù)器file_server.js

'use strict';

var
    fs = require('fs'),
    url = require('url'),
    path = require('path'),
    http = require('http');

// 從命令行參數(shù)獲取root目錄瘪撇,默認(rèn)是當(dāng)前目錄:
var root = path.resolve(process.argv[2] || '.');

console.log('Static root dir: ' + root);

// 創(chuàng)建服務(wù)器:
var server = http.createServer(function (request, response) {
    // 獲得URL的path,類似 '/css/bootstrap.css':
    var pathname = url.parse(request.url).pathname;
    // 獲得對(duì)應(yīng)的本地文件路徑,類似 '/srv/www/css/bootstrap.css':
    var filepath = path.join(root, pathname);
    // 獲取文件狀態(tài):
    fs.stat(filepath, function (err, stats) {
        if (!err && stats.isFile()) {
            // 沒有出錯(cuò)并且文件存在:
            console.log('200 ' + request.url);
            // 發(fā)送200響應(yīng):
            response.writeHead(200);
            // 將文件流導(dǎo)向response:
            fs.createReadStream(filepath).pipe(response);
        } else {
            // 出錯(cuò)了或者文件不存在:
            console.log('404 ' + request.url);
            // 發(fā)送404響應(yīng):
            response.writeHead(404);
            response.end('404 Not Found');
        }
    });
});

server.listen(8080);

console.log('Server is running at http://127.0.0.1:8080/');

命令行運(yùn)行

node file_server.js D:\workspace\js\static

瀏覽器

http://localhost:8080/static/index.html
Paste_Image.png

完整代碼

js目錄

index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Index</title>
    <link rel="stylesheet" href="css/uikit.min.css" />
    <script src="js/jquery.min.js"></script>
    <script>
    $(function () {
        $('#code').click(function () {
            window.open('https://github.com/michaelliao/learn-javascript/tree/master/samples/node/http');
        });
    });
    </script>
</head>

<body>
    <div id="header" class="uk-navbar uk-navbar-attached">
        <div class="uk-container x-container">
            <div class="uk-navbar uk-navbar-attached">
                <a href="index.html" class="uk-navbar-brand"><i class="uk-icon-home"></i> Learn Nodejs</a>
                <ul id="ul-navbar" class="uk-navbar-nav">
                    <li><a target="_blank" >JavaScript教程</a></li>
                    <li><a target="_blank" >Python教程</a></li>
                    <li><a target="_blank" >Git教程</a></li>                    
                </ul>
            </div>
        </div>
    </div><!-- // header -->

    <div id="main">
        <div class="uk-container">
            <div class="uk-grid">
                <div class="uk-width-1-1 uk-margin">
                    <h1>Welcome</h1>
                    <p><button id="code" class="uk-button uk-button-primary">Show me the code</button></p>
                </div>
            </div>
        </div>
    </div>

    <div id="footer">
        <div class="uk-container">
            <hr>
            <div class="uk-grid">
                <div class="uk-width-1-1">
                    <p>Copyright?2015-2016</p>
                </div>
            </div>
        </div>
    </div>
</body>
</html>

file_server.js

'use strict';
//node file_server.js D:\workspace\js\http\static
//http://127.0.0.1:8080/index.html
var
    fs = require('fs'),
    url = require('url'),
    path = require('path'),
    http = require('http');

var root = path.resolve(process.argv[2] || '.');
console.log('process.argv[2]: ' + process.argv[2]);// D:\workspace\js\http\static
console.log('Static root dir: ' + root);//D:\workspace\js\http\static

var server = http.createServer(function (request, response) {
    var
        pathname = url.parse(request.url).pathname,
        filepath = path.join(root, pathname);
    console.log('request.url:  ' + request.url);///index.html
    console.log('request.pathname:  ' + url.parse(request.url).pathname);//  /index.html
    console.log('filepath:  ' + filepath);//D:\workspace\js\http\static\index.html
    fs.stat(filepath, function (err, stats) {
        if (!err && stats.isFile()) {
            console.log('200 ' + request.url);
            response.writeHead(200);
            fs.createReadStream(filepath).pipe(response);
        } else {
            console.log('404 ' + request.url);
            response.writeHead(404);
            response.end('404 Not Found');
        }
    });
});

server.listen(8080);

console.log('Server is running at http://127.0.0.1:8080/');

練習(xí)

在瀏覽器輸入http://localhost:8080/ 時(shí)才漆,會(huì)返回404,原因是程序識(shí)別出HTTP請(qǐng)求的不是文件佛点,而是目錄醇滥。請(qǐng)修改file_server.js,如果遇到請(qǐng)求的路徑是目錄超营,則自動(dòng)在目錄下依次搜索index.html鸳玩、default.html,如果找到了演闭,就返回HTML文件的內(nèi)容不跟。

// 創(chuàng)建服務(wù)器:
var server = http.createServer(function (request, response) {
    // 獲得URL的path,類似 '/css/bootstrap.css':
    var pathname = url.parse(request.url).pathname;
    // 獲得對(duì)應(yīng)的本地文件路徑米碰,類似 '/srv/www/css/bootstrap.css':
    var filepath = path.join(root, pathname);
    var promise_f=function(resolve,reject){
        fs.stat(filepath, function (err, stats) {
            if (!err) {
                if(stats.isFile()){
                resolve(filepath);
                }else if(stats.isDirectory()){
                    console.log('isDirectory' + request.url);
                    var filename=path.join(root+pathname,'index.html')
                    console.log('search' + filename);
                    fs.stat(filename,function(err,stats){
                        if (!err&&stats.isFile()) {
                            resolve(filename);
                        }
                        else{
                            reject('404 ' + request.url);
                        }
                    })
                    filename=path.join(root+pathname,'default.html')
                    console.log('search' + filename);
                    fs.stat(filename,function(err,stats){
                        if (!err&&stats.isFile()) {
                            resolve(filename);
                        }else{
                            reject('404 ' + request.url);
                        }
                    })
                }
            }else{
                // 發(fā)送404響應(yīng):
                reject('404 ' + request.url);

        }
    });
};
// 獲取文件狀態(tài):
new Promise(promise_f)
.then(function(res){
    // 沒有出錯(cuò)并且文件存在:
    console.log('200 ' + request.url);
    // 發(fā)送200響應(yīng):
    response.writeHead(200);
    // 將文件流導(dǎo)向response:
    fs.createReadStream(filepath).pipe(response);
}).catch(function(err){
      // 出錯(cuò)了或者文件不存在:
        console.log('404 ' + request.url);
        response.writeHead(404);
        response.end('404 Not Found');
});
});
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末窝革,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子吕座,更是在濱河造成了極大的恐慌虐译,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,252評(píng)論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件吴趴,死亡現(xiàn)場離奇詭異漆诽,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)锣枝,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門厢拭,熙熙樓的掌柜王于貴愁眉苦臉地迎上來逃糟,“玉大人举户,你說我怎么就攤上這事。” “怎么了税朴?”我有些...
    開封第一講書人閱讀 168,814評(píng)論 0 361
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我正林,道長泡一,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,869評(píng)論 1 299
  • 正文 為了忘掉前任觅廓,我火速辦了婚禮鼻忠,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘杈绸。我一直安慰自己帖蔓,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,888評(píng)論 6 398
  • 文/花漫 我一把揭開白布瞳脓。 她就那樣靜靜地躺著塑娇,像睡著了一般。 火紅的嫁衣襯著肌膚如雪劫侧。 梳的紋絲不亂的頭發(fā)上埋酬,一...
    開封第一講書人閱讀 52,475評(píng)論 1 312
  • 那天,我揣著相機(jī)與錄音烧栋,去河邊找鬼写妥。 笑死,一個(gè)胖子當(dāng)著我的面吹牛审姓,可吹牛的內(nèi)容都是我干的珍特。 我是一名探鬼主播,決...
    沈念sama閱讀 41,010評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼邑跪,長吁一口氣:“原來是場噩夢啊……” “哼次坡!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起画畅,我...
    開封第一講書人閱讀 39,924評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤砸琅,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后轴踱,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體症脂,經(jīng)...
    沈念sama閱讀 46,469評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,552評(píng)論 3 342
  • 正文 我和宋清朗相戀三年淫僻,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了诱篷。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,680評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡雳灵,死狀恐怖棕所,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情悯辙,我是刑警寧澤琳省,帶...
    沈念sama閱讀 36,362評(píng)論 5 351
  • 正文 年R本政府宣布迎吵,位于F島的核電站,受9級(jí)特大地震影響针贬,放射性物質(zhì)發(fā)生泄漏击费。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,037評(píng)論 3 335
  • 文/蒙蒙 一桦他、第九天 我趴在偏房一處隱蔽的房頂上張望蔫巩。 院中可真熱鬧,春花似錦快压、人聲如沸圆仔。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,519評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽荧缘。三九已至,卻和暖如春拦宣,著一層夾襖步出監(jiān)牢的瞬間截粗,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,621評(píng)論 1 274
  • 我被黑心中介騙來泰國打工鸵隧, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留绸罗,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,099評(píng)論 3 378
  • 正文 我出身青樓豆瘫,卻偏偏與公主長得像珊蟀,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子外驱,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,691評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理育灸,服務(wù)發(fā)現(xiàn),斷路器昵宇,智...
    卡卡羅2017閱讀 134,711評(píng)論 18 139
  • Node.js是目前非嘲跽福火熱的技術(shù),但是它的誕生經(jīng)歷卻很奇特瓦哎。 眾所周知砸喻,在Netscape設(shè)計(jì)出JavaScri...
    w_zhuan閱讀 3,617評(píng)論 2 41
  • Node.js是目前非常火熱的技術(shù)蒋譬,但是它的誕生經(jīng)歷卻很奇特割岛。 眾所周知,在Netscape設(shè)計(jì)出JavaScri...
    Myselfyan閱讀 4,076評(píng)論 2 58
  • 個(gè)人入門學(xué)習(xí)用筆記犯助、不過多作為參考依據(jù)癣漆。如有錯(cuò)誤歡迎斧正 目錄 簡書好像不支持錨點(diǎn)、復(fù)制搜索(反正也是寫給我自己看...
    kirito_song閱讀 2,479評(píng)論 1 37
  • https://nodejs.org/api/documentation.html 工具模塊 Assert 測試 ...
    KeKeMars閱讀 6,340評(píng)論 0 6