[Node.js基礎]學習⑧--http

HTTP協議

HTTP服務器

'use strict';

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

// 創建http server,并傳入回調函數:
var server = http.createServer(function (request, response) {
    // 回調函數接收request和response對象,
    // 獲得HTTP請求的method和url:
    console.log(request.method + ': ' + request.url);
    // 將HTTP響應200寫入response, 同時設置Content-Type: text/html:
    response.writeHead(200, {'Content-Type': 'text/html'});
    // 將HTTP響應的HTML內容寫入response:
    response.end('<h1>Hello world!</h1>');
});

// 讓服務器監聽8080端口:
server.listen(8080);

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

在命令提示符下運行該程序

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

不要關閉命令提示符,直接打開瀏覽器輸入http://localhost:8080,即可看到服務器響應的內容:

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

文件服務器

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

Paste_Image.png

將一個字符串解析為一個Url對象:

'use strict';

var url = require('url');

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

結果

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

文件服務器file_server.js

'use strict';

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

// 從命令行參數獲取root目錄,默認是當前目錄:
var root = path.resolve(process.argv[2] || '.');

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

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

server.listen(8080);

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

命令行運行

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/');

練習

在瀏覽器輸入http://localhost:8080/ 時,會返回404,原因是程序識別出HTTP請求的不是文件,而是目錄。請修改file_server.js,如果遇到請求的路徑是目錄,則自動在目錄下依次搜索index.html、default.html,如果找到了,就返回HTML文件的內容。

// 創建服務器:
var server = http.createServer(function (request, response) {
    // 獲得URL的path,類似 '/css/bootstrap.css':
    var pathname = url.parse(request.url).pathname;
    // 獲得對應的本地文件路徑,類似 '/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{
                // 發送404響應:
                reject('404 ' + request.url);

        }
    });
};
// 獲取文件狀態:
new Promise(promise_f)
.then(function(res){
    // 沒有出錯并且文件存在:
    console.log('200 ' + request.url);
    // 發送200響應:
    response.writeHead(200);
    // 將文件流導向response:
    fs.createReadStream(filepath).pipe(response);
}).catch(function(err){
      // 出錯了或者文件不存在:
        console.log('404 ' + request.url);
        response.writeHead(404);
        response.end('404 Not Found');
});
});
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,993評論 19 139
  • Node.js是目前非常火熱的技術,但是它的誕生經歷卻很奇特。 眾所周知,在Netscape設計出JavaScri...
    w_zhuan閱讀 3,642評論 2 41
  • Node.js是目前非常火熱的技術,但是它的誕生經歷卻很奇特。 眾所周知,在Netscape設計出JavaScri...
    Myselfyan閱讀 4,103評論 2 58
  • 個人入門學習用筆記、不過多作為參考依據。如有錯誤歡迎斧正 目錄 簡書好像不支持錨點、復制搜索(反正也是寫給我自己看...
    kirito_song閱讀 2,505評論 1 37
  • https://nodejs.org/api/documentation.html 工具模塊 Assert 測試 ...
    KeKeMars閱讀 6,416評論 0 6