首页 > Web开发 > 详细

nodejs http网络模块

时间:2017-10-07 23:57:17      阅读:449      评论:0      收藏:0      [点我收藏+]
基本介绍

    nodejs最重要的方面之一是具有非常迅速的实现HTTP和HTTPS服务器和服务的能力。http服务是相当低层次的,你可能要用到不同的模块,如express来实现完整的Web服务器,http模块不提供处理路由、cookie、缓存等的调用。我们主要用http模块的地方是实现供应用程序使用的后端Web服务。

代码部分

主要API:

http://nodejs.cn/api/http.html

例子:

// get
/**
 * http get request
 *  http://192.168.31.162:9001?name=001&pwd=AAAaaa
 */
function createGetServer() {
    http.createServer(function(req, res){
        res.writeHead(200, {‘Content-Type‘: ‘text/plain‘});

        // 解析 url 参数
        console.log(req.url);
        var params = url.parse(req.url, true).query;
        res.write("url:" + req.url + "\n");
        res.write("Name:" + params.name + "\n");
        res.write("PWD:" + params.pwd);
        res.end();

    }).listen(9001);
}

// post
/**
 * http post request
 *  http://192.168.31.162:9002?name=001&pwd=AAAaaa
 *      psot:{"aaa":"001"}
 */
function createPostServer() {
    http.createServer(function (req, res) {
        var params = url.parse(req.url, true).query;
        var body = "";
        req.on(‘data‘, function (chunk) {
            body += chunk;
            console.log(body);
        });
        req.on(‘end‘, function () {
            // 解析参数
            // body = queryString.parse(body);
            // 设置响应头部信息及编码
            res.writeHead(200, {‘Content-Type‘: ‘text/html; charset=utf8‘});

            res.write(body);
            res.end();
        });
    }).listen(9002);
}

 

参考:

    http://nodejs.cn/api/http.html

    Node.js GET/POST请求

     Node.js Web 模块

     nodejs HTTP服务

     node/lib/_http_server.js

     node.js——http源码解读

     浅析nodejs的http模块

     NodeJS——创建最简单的HTTP服务器

 

nodejs http网络模块

原文:http://www.cnblogs.com/zhen-android/p/7636205.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!