程序员

对nodejs中http请求的理解

2016-07-09  本文已影响1165人  山药蛋Young

现在说的http请求是在最近项目中遇到的。因为刚接触node,对于这块内容还很生疏,特此纪念一下。

首先,node中本身是集成了http模块。这是顶好的一件事。

了解到的http请求有两种方式。

1. 使用request模块

优点开发迅速;缺点需要额外安装request模块。node本身是没有这个模块的。


○ npm install request

安装完成之后,就可以使用request模块了。


var request = require('request');
var querystring = require('querystring');

function requestPost(param1,param2) {
    var data = {
        username: param1,
        password: param2
    };
    var formData = querystring.stringify(data);
    request.post({
        headers: {
            'content-type' : 'application/x-www-form-urlencoded',
            'Content-Length' : formData.length
        },
        url:    'http://api_address',
        body:    formData
    }, function(error, response, body){
        console.log(body);
    });
}

在这段代码中hearders指明协议头的数据信息,application/x-www-form-urlencoded说明了编码格式。url是接口访问地址。body是在做POST请求时才需要,如果是做get请求,body可以忽略。

2. 使用自身的http模块

因为node本身带有了http模块,所以直接引入使用即可。

var http = require('http');
var url  = require('url');
var querystring = require('querystring');
function updateStreamStatus(param1,param2) {
    var strUpdateUrl = "http://api_address";
    var parse = url.parse(strUpdateUrl);
    var data = { username: param1, password: param2 };
    var formData = querystring.stringify(data);
    var options = {
        "method" : "POST",
        "host" : parse.hostname,
        "path" : parse.path,
        "body" : formData,
        "headers" : {
            'Content-Type': 'application/x-www-form-urlencoded',
            "Content-Length" : formData.length
        }
    }
    console.log(`PARAM : ${options}`);
    var req = http.request(options, function(res) {
        console.log(`STATUS: ${res.statusCode}`);
        if (res.statusCode == 200) {
            res.setEncoding("utf-8");
            var resData = "";
            res.on("data", function(chunk) {
                resData += chunk;
            }).on("end", function() {
                console.log(resData);
            });
        } else {
            //请求失败
            console.log("res.statusCode err " + res.statusCode);
        }
    }); 

    req.write(formData);
    req.end();
}

在这段代码中,使用url模块,其主要作用就是做地址解析。host是解析后的域名[不带http],path是接口地址[去除域名部分剩余的],body是post的参数体,header中定义了'Content-Length'为参数体长度。

需要注意的是,由于这种方式的请求方式通过method的方式作为request的参数传递过去的。所以,做GET或者POST要单独标明。

ps:本文第二种方式中使用了两种方式的console方式。后续将单独说明一下。

上一篇 下一篇

猜你喜欢

热点阅读