[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" href="http://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000">JavaScript教程</a></li>
                    <li><a target="_blank" href="http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000">Python教程</a></li>
                    <li><a target="_blank" href="http://www.liaoxuefeng.com/wiki/0013739516305929606dd18361248578c67b8067c8c017b000">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');
});
});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • Node.js是目前非常火热的技术,但是它的诞生经历却很奇特。 众所周知,在Netscape设计出JavaScri...
    w_zhuan阅读 3,578评论 2 41
  • Node.js是目前非常火热的技术,但是它的诞生经历却很奇特。 众所周知,在Netscape设计出JavaScri...
    Myselfyan阅读 4,041评论 2 58
  • 个人入门学习用笔记、不过多作为参考依据。如有错误欢迎斧正 目录 简书好像不支持锚点、复制搜索(反正也是写给我自己看...
    kirito_song阅读 2,419评论 1 37
  • https://nodejs.org/api/documentation.html 工具模块 Assert 测试 ...
    KeKeMars阅读 6,221评论 0 6