nodejs模块——http模块

http模块主要用于创建http server服务,并且

  • 支持更多特性
  • 不缓冲请求和响应
  • 处理流相关

本文还用到url模块path模块,还有fs模块。url模块用于解析url,path模块用于处理和转换文件路径

一、简单应用

代码如下:

// 文件名:demo.js

// 引入http模块
var http = require('http');

// 创建http server
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World\n');
}).listen(1337, '127.0.0.1');

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

$ node demo.js运行后,在浏览器可看到Hello World。

通过简单的http.createServer()创建一个server,通过server.on绑定事件处理函数,通过server.listen监听。 一个简单的http服务器就完成了。

二、稍复杂应用

 所以代码放在app文件夹汇总,如下。

 

 1、server.js

功能:创建http服务,监听请求,让route处理。

//
// 创建http server
//

// 加载所需模块
var http = require('http');
var url = require('url');
var fs = require('fs');

// 设置ip和端口
// 实际应用中,可以把这些写到配置文件中
var host = '127.0.0.1',
    port = 8080;

// 创建http server
function start(route, handle) {
    // 参数
    // route  判断url是否存在,存在则调用handle处理,不存在则返回404
    // handle 处理不同的url请求


    // 处理request请求
    function onRequest(req, res) {
        // 使用url.parse()方法解析url
        // 它会把url string转化为一个object
        // 这样我们就可以很方便的获取url中的host、port、pathname等值了
        var pathname = url.parse(req.url).pathname;
        console.log('Request for ' + pathname + ' received.');

        // 判断并处理不同url请求
        // 后面介绍此方法
        route(handle, pathname, res, req);
    }

    // 使用http.createSserver()方法创建http server
    // 并传入onRequest()方法
    // 然后使用listen()方法监听指定地址
    http.createServer(onRequest).listen(port, host);
    console.log('Server has started and listening on ' + host + ':' + port);
}

// 导出 start 方法
exports.start = start;
View Code

server.js中用到了http模块、url模块和fs模块。

 使用url.parse()方法解析url,把url string转化为一个object,这样我们就可以很方便的获取url中的host,port,pathanme等值了。

 var pathname = url.parse(request.url).pathname;

例:请求url:127.0.0.1:8088/about时req.url为:/about 。

 

 最后导出start方法以便在主程序中使用。

2、router.js

功能: route判断url是否存在,存在则调用handle处理,不存在则返回404。

var fs = require('fs');

// 路由函数
// 处理不同url的请求
// 并返回相应内容

function route(handle, pathname, res, req) {
    console.log('About to route a request for ' + pathname);

    // 判断此url是否存在特定处理函数
    // 存在则调用handle处理
    // 不存在则返回404页面
    if (typeof handle[pathname] === 'function') {
        // 后面介绍handle函数
        handle[pathname](res, req);
    } else {
        console.log('No request handler found for ' + pathname);

        // 读取404页面
        // 所有页面都存放在view文件夹下
        var content = fs.readFileSync('./views/404.html');
        res.writeHead(404, { 'Content-Type': 'text/html' });
        res.write(content);
        res.end();
    }
}
// 导出 route 方法
exports.route = route;
View Code

路由转发,如果url存在(通过handle判断的)交由handle处理,否则返回404页面。

3、requestHandlers.js

功能:handle处理不同的url请求。

代码如下:

// 处理url请求

var fs = require('fs');

// home.html 主页
function home(res) {
    console.log('Request handler "home" was called.');

    // 读取home.html文件
    var content = fs.readFileSync('./views/home.html');
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.write(content);
    res.end();
}

// about.html 关于页面
function about(res) {
    console.log('Request handler "about" was called.');

    // 读取about.html文件
    var content = fs.readFileSync('./views/about.html');
    res.write(200, { 'Content-Type': 'text/html' });
    res.write(content);
    res.end();
}

// 导出页面处理函数
exports.home = home;
exports.about = about;
View Code

4、主程序main.js

上面是创建http server,判断url,处理url。

现在写主程序来运行http server,代码如下:

// 主程序

// 引入server,router及requestHandler
var server = require('./server');
var router = require('./router');
var requestHandlers = require('./requestHandlers');

// 保存url处理方法
var handle = {};
handle['/'] = requestHandlers.home;
handle['/about'] = requestHandlers.about;

// 启动http server
server.start(router.route, handle);

至此,所有服务器代码写完。

5、 用到的html文件

app文件夹的的views文件夹下,创建home.html,about.html和404.html如下。

home.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>Home page</title>
    </head>
    <body>
        <p>home page</p>
    </body>
</html>

about.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>About page</title>
    </head>
    <body>
        <p>about page</p>
    </body>
</html>

404.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>404 page</title>
    </head>
    <body>
        <p>404 page not found</p>
    </body>
</html>

6、运行程序

$ node main.js

访问http://127.0.0.1:8080会看到home page页面。

访问http://127.0.0.1:8080/about显示about page页面。

其他显示404 page 页面。

三、排错

错误1:

throw er; // Unhandled 'error' event

出现这种错误一般就是已经运行的另一个服务器使用了相同的端口,换一个端口就可以了。

 
本文作者starof,因知识本身在变化,作者也在不断学习成长,文章内容也不定时更新,为避免误导读者,方便追根溯源,请诸位转载注明出处:http://www.cnblogs.com/starof/p/5038890.html有问题欢迎与我讨论,共同进步。

posted @ 2015-12-18 11:23  starof  阅读(10049)  评论(0编辑  收藏  举报