Node中的HTTP请求

72 篇文章 0 订阅
61 篇文章 0 订阅

HTTP请求,有时候是个很简单的请求,只是简单的接口调用罢了,有时候却也是挺麻烦的东西,现在结合我最近做cloudCode的契机将node中http请求做一个总结,遗留的问题后面再做详细的研究:
1、Node内置的HTTP请求
首先引入http module,

var http = require(‘http’);
在介绍http的具体用法之前,我们先看下node官网关于它的用法,https://nodejs.org/api/http.html#http_http_request_options_callback
1

根据api的说明就有了下面的配置:

data = {“subject”:”test”,”message”:”message”,”addresses”:”houyaowei@163.com”};
var options = {
host: ‘127.0.0.1’,
port: 8080,
path: ‘/mobilePlatform/1/mailing/send’,
method: ‘POST’,
headers:{
‘accept’: ‘application/json’,
‘content-type’: ‘application/json; charset=utf-8’,
‘X-MA-Application-Id’: ‘553f42a002f4192de7b4541d’,
‘X-MA-REST-API-Key’: ‘25e267bc9ffc4a8da4626e7387c5fd2d’,
‘user-agent’: ‘nodejs rest client’,
‘Content-Length’: require(‘querystring’).parse(data).length
}
};
var req = https.request(options, function(res) {
console.log(“Got response: ” + res.statusCode);
var body = ”;
res.on(‘data’,function(d){
body += d;
}).on(‘end’, function(){
console.log(res.headers)
});
}).on(‘error’, function(e) {
console.log(“Got error: ” + e.message);
});
req.write(data);
req.end();

这样的用法还是很复杂的,当然和使用场景有关,比如说设置header等。当然如果对于没有请求体的get请求,可以使用简略的形式,用法如下:

http.get(“http://www.google.com/index.html“, function(res) {
console.log(“Got response: ” + res.statusCode);
}).on(‘error’, function(e) {
console.log(“Got error: ” + e.message);
});
2、初步使用needle(npm module)
github地址:https://github.com/tomas/needle,也可以通过npm搜索needle找到用法。
首先还是引入module

var needle = require(‘needle’);
needle的接口形式如下:

needle.post(url, data, [options,] callback)
所以needle的用法可以使用如下配置:

data = {“subject”:”test”,”message”:”message”,”addresses”:”houyaowei@163.com”};
url = ‘127.0.0.1:8080/mobilePlatform/1/mailing/send’;
var options = {
headers:{
‘accept’: ‘application/json’,
‘content-type’: ‘application/json; charset=utf-8’,
‘X-MA-Application-Id’: ‘553f42a002f4192de7b4541d’,
‘X-MA-REST-API-Key’: ‘25e267bc9ffc4a8da4626e7387c5fd2d’,
‘user-agent’: ‘nodejs rest client’,
‘Content-Length’: require(‘querystring’).parse(data).length
}
};
needle.post(url, data, options, function(err, resp) {

      if(resp.statusCode === 200){
          callback(null,'Execute Successfully');
      } else {
          callback(null,'Execute Failed');
      }
  });

通过阅读needle可以发现,虽然发送请求的data为object,但是needle在发送前会转换成string,如果服务端是接受object的,它就显得不合适了。
3、初步使用unirest(npm module),和needle使用相似,此处省略。
4、初步使用request(npm module),推荐使用,request的配置灵活并且功能强大
github地址:https://github.com/request/request
用法如下:

data = {“subject”:”test”,”message”:”message11111111111111111111111111111”,”addresses”:”houyaowei@163.com”};
request({
url: “http://192.168.82.153:8080/mobilePlatform/1/mailing/send“,
method: “POST”,
json: true,
body: data,
headers:{
‘accept’: ‘application/json’,
‘content-type’: ‘application/json; charset=utf-8’,
‘X-MA-Application-Id’: ‘553f42a002f4192de7b4541d’,
‘X-MA-REST-API-Key’: ‘25e267bc9ffc4a8da4626e7387c5fd2d’,
‘user-agent’: ‘nodejs rest client’,
‘Content-Length’: require(‘querystring’).parse(data).length
}
}, function (error, response, body){
if(response.statusCode === 200){
callback(null,’Execution successfully!’);
}else{
callback(null,’Execution failed!’);
}
});
从上面的代码看不出request的强大之处。这里需要注意的是,如果你想发送json对象,就需要设置json:true,这里类似是一个开关。除了json,request还支持xml形式,如果要发送xml,需要将在header中增加

“content-type”: “application/xml”
这个非常重要,否则以string发送。另外request还支持如下特性:
(1)请求的简易写法 request.post();
(2)管道方式:request(‘http://google.com/doodle.png’).pipe(fs.createWriteStream(‘doodle.png’))
(3)Form表单形式
(4)HTTP验证
(5)TSL/SSL 协议
(6)UNIX domain request.get(‘http://unix:/absolute/path/to/unix.socket:/request/path’)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值