HTTP客户端之使用request方法向其他网站请求数据

在node中,可以很轻松的向任何网站发送请求并读取该网站的响应数据.

var req=http.request(options,callback);

options是一个字符串或者是对象.如果是字符串,将自动使用url模块中的parse方法转换为一个对象.options中可以指定以下属性.

host:用于指定域名或目标主机的IP地址,默认属性值为"localhost".

hostname:用于指定域名或目标主机的IP地址,默认属性为"localhost".如果hostname属性值与host属性值都被指定,优先使用hostname.

port:用于指定目标服务器用于HTTP客户端连接的端口号.

localAddress:用于指定专用于网络连接的本地接口.

socketPath:用于指定目标Unix域端口.

method:用于指定HTTP请求方式,默认属性值为"GET".

path:用于指定路径及查询字符串,默认属性值为"/".

headers:用于指定客户端请求头对象.

auth:用于指定认证信息部分.例如:"user:password".

agent:用于指定HTTP代理.在node中,使用http.Agent类代表一个HTTP代理.所谓HTTP代理,就是一个代表通过HTTP向其他网站请求数据的浏览器或者代理服务器.

在node中,HTTP代理默认在请求数据时使用keep-alive连接,同时使用一个全局的http.Agent对象来实现所有HTTP客户端请求.不使用agent属性值时,默认使用该全局http.Agent对象.可以为agent属性值显示指定一个http.Agent对象(即用户代理),也可以通过将agent属性值指定为false的方法从连接池中自动挑选一个当前连接状态为关闭的http.Agent对象(即用户代理)

 1 var http=require("http");
 2 var options={
 3   hostname:"www.baidu.com",
 4     port:80,
 5     path:"/",
 6     method:"GET"
 7 };
 8 var req=http.request(options,function(res){
 9     console.log("状态码:"+res.statusCode);
10     console.log("响应头:"+JSON.stringify(res.headers));
11     res.setEncoding("utf8");
12     res.on("data",function(chunk){
13         console.log("响应内容:"+chunk);
14     });
15 });
16 req.end();

HTTP客户端设置超时和终止请求,并且用error监听socket端口错误.

 1 var http=require("http");
 2 var options={
 3     hostname:"www.baiduuuuuuu.com",//这是一个不存在的网址
 4     port:80,
 5     path:"/",
 6     method:"GET"
 7 };
 8 var req=http.request(options,function(res){
 9     console.log("状态码:"+res.statusCode);
10     console.log("响应头:"+JSON.stringify(res.headers));
11     res.setEncoding("utf8");
12     res.on("data",function(chunk){
13         console.log("响应内容:"+chunk);
14     });
15 });
16 req.setTimeout(1000,function(){
17     req.abort();
18 });
19 req.on("error",function(err){
20     if(err.code==="ECONNRESET")//端口的超时错误
21         console.log("socket端口超时..");
22     else
23         console.log("在请求数据的过程中发生错误,错误代码:"+err.code);
24 });
25 req.end();

get方法向其他网站发送请求时和request的方法一样.不过get不需要手动调用end()方法,node会自动调用end().

可以对上面的代码做一下改动.

 1 var http=require("http");
 2 var options={
 3     hostname:"www.baiduuuuuuu.com",//这是一个不存在的网址
 4     port:80,
 5     path:"/",
 6     method:"GET"
 7 };
 8 var req=http.get(options,function(res){
 9     console.log("状态码:"+res.statusCode);
10     console.log("响应头:"+JSON.stringify(res.headers));
11     res.setEncoding("utf8");
12     res.on("data",function(chunk){
13         console.log("响应内容:"+chunk);
14     });
15 });
16 
17 req.setTimeout(1000,function(){
18     req.abort();console.log("终止亲求");
19 });
20 req.on("error",function(err){
21     if(err.code==="ECONNRESET")//端口的超时错误
22         console.log("socket端口超时..");
23     else
24         console.log("在请求数据的过程中发生错误,错误代码:"+err.code);
25 });
原文地址:https://www.cnblogs.com/guoyansi19900907/p/4066916.html