Nodejs:http入门2:发送get请求

最简单的一个请求,莫过于我们发一个get请求,(这个是我自己理解的最简单)

接下来就上代码吧:

var http=require('https');  
//get 请求外网  
http.get('https://www.baidu.com',function(req,res){  
    var html='';  
	console.log("已经发送请求");
	 //通过req的data事件监听函数,每当接受到请求体的数据,就累加到post变量中
    req.on('data',function(data){
	console.log("\n\n\n");
	console.log("这次返回的数据是")		
	//注意,这儿返回的是buffer,具体看文档:http://nodejs.cn/api/buffer.html
	console.log(data);
	html+=data;  		
    });  
	//end事件
    req.on('end',function(){  
	console.log("\n\n\n"); 
	console.log("最后返回的整体数据是:");
	console.log(html);		
    });  
}); 

注释写了一些,我想应该够用了,其实也是很简单,但是这个是使用的http.get方法,当然不是今后才说的http。request方法

效果图的话是这样的:

Microsoft Windows [版本 6.1.7601]
版权所有 (c) 2009 Microsoft Corporation。保留所有权利。

C:\Users\mk>d:

D:\>cd nodejs

D:\nodejs>node d/code/nodejs/node-http-get-send.js
module.js:538
    throw err;
    ^

D:\nodejs>node d:/code/nodejs/node-http-get-send.js
已经发送请求




这次返回的数据是
<Buffer 3c 21 44 4f 43 54 59 50 45 20 68 74 6d 6c 3e 3c 21 2d 2d 53 54 41 54 55
53 20 4f 4b 2d 2d 3e 0d 0a 3c 68 74 6d 6c 3e 0d 0a 3c 68 65 61 64 3e 0d 0a 09 ..
. >




这次返回的数据是
<Buffer 62 61 69 64 75 2e 63 6f 6d 2f 76 3f 63 74 3d 33 30 31 39 38 39 38 38 38
26 72 6e 3d 32 30 26 70 6e 3d 30 26 64 62 3d 30 26 73 3d 32 35 26 77 6f 72 64 ..
. >




这次返回的数据是
<Buffer 27 3a 27 74 61 62 27 2c 27 74 61 62 27 3a 27 76 69 64 65 6f 27 7d 29 22
3e e8 a7 86 e9 a2 91 3c 2f 61 3e 26 23 31 32 32 38 38 3b 3c 61 20 68 72 65 66 ..
. >




这次返回的数据是
<Buffer ba a6 e8 ae be e4 b8 ba e4 b8 bb e9 a1 b5 3c 2f 61 3e 3c 61 20 69 64 3d
22 73 65 74 66 22 20 68 72 65 66 3d 22 2f 2f 77 77 77 2e 62 61 69 64 75 2e 63 ..
. >




这次返回的数据是
<Buffer 72 2e 61 64 64 43 6c 61 73 73 28 27 69 70 74 68 6f 76 65 72 27 29 3b 7d
29 2e 6f 6e 28 27 6d 6f 75 73 65 6f 75 74 27 2c 66 75 6e 63 74 69 6f 6e 28 29 ..
. >




最后返回的整体数据是:
<!DOCTYPE html><!--STATUS OK-->
<html>
<head>
        <meta http-equiv="content-type" content="text/html;charset=utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=Edge">
        <link rel="dns-prefetch" href="//s1.bdstatic.com"/>
        <link rel="dns-prefetch" href="//t1.baidu.com"/>
        <link rel="dns-prefetch" href="//t2.baidu.com"/>
        <link rel="dns-prefetch" href="//t3.baidu.com"/>
        <link rel="dns-prefetch" href="//t10.baidu.com"/>
        <link rel="dns-prefetch" href="//t11.baidu.com"/>
        <link rel="dns-prefetch" href="//t12.baidu.com"/>
        <link rel="dns-prefetch" href="//b1.bdstatic.com"/>
        <title>百度一下,你就知道</title>
        <link href="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/st
atic/home/css/index.css" rel="stylesheet" type="text/css" />
        <!--[if lte IE 8]><style index="index" >#content{height:480px\9}#m{top:2
60px\9}</style><![endif]-->
        <!--[if IE 8]><style index="index" >#u1 a.mnav,#u1 a.mnav:visited{font-f
amily:simsun}</style><![endif]-->
        <script>var hashMatch = document.location.href.match(/#+(.*wd=[^&].+)/);
if (hashMatch && hashMatch[0] && hashMatch[1]) {document.location.replace("http:
//"+location.host+"/s?"+hashMatch[1]);}var ns_c = function(){};</script>
        <script>function h(obj){obj.style.behavior='url(#default#homepage)';var
a = obj.setHomePage('//www.baidu.com/');}</script>
        <noscript><meta http-equiv="refresh" content="0; url=/baidu.html?from=no
script"/></noscript>
        <script>window._ASYNC_START=new Date().getTime();</script>
</head>
<body link="#0000cc"><div id="wrapper" style="display:none;"><div id="u"><a href
="//www.baidu.com/gaoji/preferences.html"  οnmοusedοwn="return user_c({'fm':'set
','tab':'setting','login':'0'})">搜索设置</a>|<a id="btop" href="/"  onmousedown
="return user_c({'fm':'set','tab':'index','login':'0'})">百度首页</a>|<a id="lb"
 href="https://passport.baidu.com/v2/?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%
2F" οnclick="return false;"  οnmοusedοwn="return user_c({'fm':'set','tab':'login
'})">登录</a><a href="https://passport.baidu.com/v2/?reg&regType=1&tpl=mn&u=http
%3A%2F%2Fwww.baidu.com%2F"  οnmοusedοwn="return user_c({'fm':'set','tab':'reg'})
" target="_blank" class="reg">注册</a></div><div id="head"><div class="s_nav"><a
 href="/" class="s_logo" οnmοusedοwn="return c({'fm':'tab','tab':'logo'})"><img
src="//www.baidu.com/img/baidu_jgylogo3.gif" width="117" height="38" border="0"
alt="到百度首页" title="到百度首页"></a><div class="s_tab" id="s_tab"><a href="h
ttp://news.baidu.com/ns?cl=2&rn=20&tn=news&word=" wdfield="word"  οnmοusedοwn="r
eturn c({'fm':'tab','tab':'news'})">新闻</a> <b>网页</b> <a href="
http://tieba.baidu.com/f?kw=&fr=wwwt" wdfield="kw"  οnmοusedοwn="return c({'fm':
'tab','tab':'tieba'})">贴吧</a> <a href="http://zhidao.baidu.com/q?ct=17&
pn=0&tn=ikaslist&rn=10&word=&fr=wwwt" wdfield="word"  οnmοusedοwn="return c({'fm
':'tab','tab':'zhidao'})">知道</a> <a href="http://music.baidu.com/search
?fr=ps&key=" wdfield="key"  οnmοusedοwn="return c({'fm':'tab','tab':'music'})">
音乐</a> <a href="http://image.baidu.com/i?tn=baiduimage&ps=1&ct=20132659
2&lm=-1&cl=2&nc=1&word=" wdfield="word"  οnmοusedοwn="return c({'fm':'tab','tab'
:'pic'})">图片</a> <a href="http://v.baidu.com/v?ct=301989888&rn=20&pn=0&
db=0&s=25&word=" wdfield="word"   οnmοusedοwn="return c({'fm':'tab','tab':'video
'})">视频</a> <a href="http://map.baidu.com/m?word=&fr=ps01000" wdfield="
word"  οnmοusedοwn="return c({'fm':'tab','tab':'map'})">地图</a> <a href=
"http://wenku.baidu.com/search?word=&lm=0&od=0" wdfield="word"  οnmοusedοwn="ret
urn c({'fm':'tab','tab':'wenku'})">文库</a> <a href="//www.baidu.com/more
/"  οnmοusedοwn="return c({'fm':'tab','tab':'more'})">更多»</a></div></div><form
 id="form" name="f" action="/s" class="fm" ><input type="hidden" name="ie" value
="utf-8"><input type="hidden" name="f" value="8"><input type="hidden" name="rsv_
bp" value="1"><span class="bg s_ipt_wr"><input name="wd" id="kw" class="s_ipt" v
alue="" maxlength="100"></span><span class="bg s_btn_wr"><input type="submit" id
="su" value="百度一下" class="bg s_btn" οnmοusedοwn="this.className='bg s_btn s_
btn_h'" οnmοuseοut="this.className='bg s_btn'"></span><span class="tools"><span
id="mHolder"><div id="mCon"><span>输入法</span></div><ul id="mMenu"><li><a href=
"javascript:;" name="ime_hw">手写</a></li><li><a href="javascript:;" name="ime_p
y">拼音</a></li><li class="ln"></li><li><a href="javascript:;" name="ime_cl">关
闭</a></li></ul></span><span class="shouji"><strong>推荐 : </strong><a
 href="http://w.x.baidu.com/go/mini/8/10000020" οnmοusedοwn="return ns_c({'fm':'
behs','tab':'bdbrowser'})">百度浏览器,打开网页快2秒!</a></span></span></form><
/div><div id="content"><div id="u1"><a href="http://news.baidu.com" name="tj_trn
ews" class="mnav">新闻</a><a href="http://www.hao123.com" name="tj_trhao123" cla
ss="mnav">hao123</a><a href="http://map.baidu.com" name="tj_trmap" class="mnav">
地图</a><a href="http://v.baidu.com" name="tj_trvideo" class="mnav">视频</a><a h
ref="http://tieba.baidu.com" name="tj_trtieba" class="mnav">贴吧</a><a href="htt
ps://passport.baidu.com/v2/?login&tpl=mn&u=http%3A%2F%2Fwww.baidu.com%2F" name="
tj_login" id="lb" οnclick="return false;">登录</a><a href="//www.baidu.com/gaoji
/preferences.html" name="tj_settingicon" id="pf">设置</a><a href="//www.baidu.co
m/more/" name="tj_briicon" id="bri">更多产品</a></div><div id="m"><p id="lg"><im
g src="//www.baidu.com/img/bd_logo.png" width="270" height="129"></p><p id="nv">
<a href="http://news.baidu.com">新 闻</a> <b>网 页</b> <a href="http
://tieba.baidu.com">贴 吧</a> <a href="http://zhidao.baidu.com">知 道
</a> <a href="http://music.baidu.com">音 乐</a> <a href="http://image.bai
du.com">图 片</a> <a href="http://v.baidu.com">视 频</a> <a href="ht
tp://map.baidu.com">地 图</a></p><div id="fm"><form id="form1" name="f1" ac
tion="/s" class="fm"><span class="bg s_ipt_wr"><input type="text" name="wd" id="
kw1" maxlength="100" class="s_ipt"></span><input type="hidden" name="rsv_bp" val
ue="0"><input type=hidden name=ch value=""><input type=hidden name=tn value="bai
du"><input type=hidden name=bar value=""><input type="hidden" name="rsv_spt" val
ue="3"><input type="hidden" name="ie" value="utf-8"><span class="bg s_btn_wr"><i
nput type="submit" value="百度一下" id="su1" class="bg s_btn" οnmοusedοwn="this.
className='bg s_btn s_btn_h'" οnmοuseοut="this.className='bg s_btn'"></span></fo
rm><span class="tools"><span id="mHolder1"><div id="mCon1"><span>输入法</span></
div></span></span><ul id="mMenu1"><div class="mMenu1-tip-arrow"><em></em><ins></
ins></div><li><a href="javascript:;" name="ime_hw">手写</a></li><li><a href="jav
ascript:;" name="ime_py">拼音</a></li><li class="ln"></li><li><a href="javascrip
t:;" name="ime_cl">关闭</a></li></ul></div><p id="lk"><a href="http://baike.baid
u.com">百科</a> <a href="http://wenku.baidu.com">文库</a> <a href="http://www.
hao123.com">hao123</a><span> | <a href="//www.baidu.com/more/">更多>
;></a></span></p><p id="lm"></p></div></div><div id="ftCon"><div id="ftConw">
<p id="lh"><a id="seth" onClick="h(this)" href="/" οnmοusedοwn="return ns_c({'fm
':'behs','tab':'homepage','pos':0})">把百���设为主页</a><a id="setf" href="//www
.baidu.com/cache/sethelp/index.html" οnmοusedοwn="return ns_c({'fm':'behs','tab'
:'favorites','pos':0})" target="_blank">把百度设为主页</a><a οnmοusedοwn="return
 ns_c({'fm':'behs','tab':'tj_about'})" href="http://home.baidu.com">关于百度</a>
<a οnmοusedοwn="return ns_c({'fm':'behs','tab':'tj_about_en'})" href="http://ir.
baidu.com">About Baidu</a></p><p id="cp">&copy;2017 Baidu <a href="/du
ty/" name="tj_duty">使用百度前必读</a> 京ICP证030173号 <img src="http:
//s1.bdstatic.com/r/www/cache/static/global/img/gs_237f015b.gif"></p></div></div
><div id="wrapper_wrapper"></div></div><div class="c-tips-container" id="c-tips-
container"></div>
<script>window.__async_strategy=2;</script>
<script>var bds={se:{},su:{urdata:[],urSendClick:function(){}},util:{},use:{},co
mm : {domain:"http://www.baidu.com",ubsurl : "http://sclick.baidu.com/w.gif",tn:
"baidu",queryEnc:"",queryId:"",inter:"",templateName:"baidu",sugHost : "http://s
uggestion.baidu.com/su",query : "",qid : "",cid : "",sid : "",indexSid : "",stok
en : "",serverTime : "",user : "",username : "",loginAction : [],useFavo : "",pi
nyin : "",favoOn : "",curResultNum:"",rightResultExist:false,protectNum:0,zxlNum
:0,pageNum:1,pageSize:10,newindex:0,async:1,maxPreloadThread:5,maxPreloadTimes:1
0,preloadMouseMoveDistance:5,switchAddMask:false,isDebug:false,ishome : 1},_base
64:{domain : "http://b1.bdstatic.com/",b64Exp : -1,pdc : 0}};var name,navigate,a
l_arr=[];var selfOpen = window.open;eval("var open = selfOpen;");var isIE=naviga
tor.userAgent.indexOf("MSIE")!=-1&&!window.opera;var E = bds.ecom= {};bds.se.mon
 = {'loadedItems':[],'load':function(){},'srvt':-1};try {bds.se.mon.srvt = parse
Int(document.cookie.match(new RegExp("(^| )BDSVRTM=([^;]*)(;|$)"))[2]);document.
cookie="BDSVRTM=;expires=Sat, 01 Jan 2000 00:00:00 GMT"; }catch(e){}</script>
<script>if(!location.hash.match(/[^a-zA-Z0-9]wd=/)){document.getElementById("ftC
on").style.display='block';document.getElementById("u1").style.display='block';d
ocument.getElementById("content").style.display='block';document.getElementById(
"wrapper").style.display='block';setTimeout(function(){try{document.getElementBy
Id("kw1").focus();document.getElementById("kw1").parentNode.className += ' iptfo
cus';}catch(e){}},0);}</script>
<script type="text/javascript" src="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3
K/r/www/cache/static/protocol/https/jquery/jquery-1.10.2.min_f2fb5194.js"></scri
pt>
<script>(function(){var index_content = $('#content');var index_foot= $('#ftCon'
);var index_css= $('head [index]');var index_u= $('#u1');var result_u= $('#u');v
ar wrapper=$("#wrapper");window.index_on=function(){index_css.insertAfter("meta:
eq(0)");result_common_css.remove();result_aladdin_css.remove();result_sug_css.re
move();index_content.show();index_foot.show();index_u.show();result_u.hide();wra
pper.show();if(bds.su&&bds.su.U&&bds.su.U.homeInit){bds.su.U.homeInit();}setTime
out(function(){try{$('#kw1').get(0).focus();window.sugIndex.start();}catch(e){}}
,0);if(typeof initIndex=='function'){initIndex();}};window.index_off=function(){
index_css.remove();index_content.hide();index_foot.hide();index_u.hide();result_
u.show();result_aladdin_css.insertAfter("meta:eq(0)");result_common_css.insertAf
ter("meta:eq(0)");result_sug_css.insertAfter("meta:eq(0)");wrapper.show();};})()
;</script>
<script>window.__switch_add_mask=1;</script>
<script type="text/javascript" src="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3
K/r/www/cache/static/global/js/instant_search_newi_redirect1_20bf4036.js"></scri
pt>
<script>initPreload();$("#u,#u1").delegate("#lb",'click',function(){try{bds.se.l
ogin.open();}catch(e){}});if(navigator.cookieEnabled){document.cookie="NOJS=;exp
ires=Sat, 01 Jan 2000 00:00:00 GMT";}</script>
<script>$(function(){for(i=0;i<3;i++){u($($('.s_ipt_wr')[i]),$($('.s_ipt')[i]),$
($('.s_btn_wr')[i]),$($('.s_btn')[i]));}function u(iptwr,ipt,btnwr,btn){if(iptwr
 && ipt){iptwr.on('mouseover',function(){iptwr.addClass('ipthover');}).on('mouse
out',function(){iptwr.removeClass('ipthover');}).on('click',function(){ipt.focus
();});ipt.on('focus',function(){iptwr.addClass('iptfocus');}).on('blur',function
(){iptwr.removeClass('iptfocus');}).on('render',function(e){var $s = iptwr.paren
t().find('.bdsug');var l = $s.find('li').length;if(l>=5){$s.addClass('bdsugbg');
}else{$s.removeClass('bdsugbg');}});}if(btnwr && btn){btnwr.on('mouseover',funct
ion(){btn.addClass('btnhover');}).on('mouseout',function(){btn.removeClass('btnh
over');});}}});</script>
<script type="text/javascript" src="https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3
K/r/www/cache/static/home/js/bri_7f1fa703.js"></script>
<script>(function(){var _init=false;window.initIndex=function(){if(_init){return
;}_init=true;var w=window,d=document,n=navigator,k=d.f1.wd,a=d.getElementById("n
v").getElementsByTagName("a"),isIE=n.userAgent.indexOf("MSIE")!=-1&&!window.oper
a;(function(){if(/q=([^&]+)/.test(location.search)){k.value=decodeURIComponent(R
egExp["\x241"])}})();(function(){var u = G("u1").getElementsByTagName("a"), nv =
 G("nv").getElementsByTagName("a"), lk = G("lk").getElementsByTagName("a"), un =
 "";var tj_nv = ["news","tieba","zhidao","mp3","img","video","map"];var tj_lk =
["baike","wenku","hao123","more"];un = bds.comm.user == "" ? "" : bds.comm.user;
function _addTJ(obj){addEV(obj, "mousedown", function(e){var e = e || window.eve
nt;var target = e.target || e.srcElement;if(target.name){ns_c({'fm':'behs','tab'
:target.name,'un':encodeURIComponent(un)});}});}for(var i = 0; i < u.length; i++
){_addTJ(u[i]);}for(var i = 0; i < nv.length; i++){nv[i].name = 'tj_' + tj_nv[i]
;}for(var i = 0; i < lk.length; i++){lk[i].name = 'tj_' + tj_lk[i];}})();(functi
on() {var links = {'tj_news': ['word', 'http://news.baidu.com/ns?tn=news&cl=2&rn
=20&ct=1&ie=utf-8'],'tj_tieba': ['kw', 'http://tieba.baidu.com/f?ie=utf-8'],'tj_
zhidao': ['word', 'http://zhidao.baidu.com/search?pn=0&rn=10&lm=0'],'tj_mp3': ['
key', 'http://music.baidu.com/search?fr=ps&ie=utf-8'],'tj_img': ['word', 'http:/
/image.baidu.com/i?ct=201326592&cl=2&nc=1&lm=-1&st=-1&tn=baiduimage&istype=2&fm=
&pv=&z=0&ie=utf-8'],'tj_video': ['word', 'http://video.baidu.com/v?ct=301989888&
s=25&ie=utf-8'],'tj_map': ['wd', 'http://map.baidu.com/?newmap=1&ie=utf-8&s=s'],
'tj_baike': ['word', 'http://baike.baidu.com/search/word?pic=1&sug=1&enc=utf8'],
'tj_wenku': ['word', 'http://wenku.baidu.com/search?ie=utf-8']};var domArr = [G(
'nv'), G('lk'),G('cp')],kw = G('kw1');for (var i = 0, l = domArr.length; i < l;
i++) {domArr[i].onmousedown = function(e) {e = e || window.event;var target = e.
target || e.srcElement,name = target.getAttribute('name'),items = links[name],re
g = new RegExp('^\\s+|\\s+\x24'),key = kw.value.replace(reg, '');if (items) {if
(key.length > 0) {var wd = items[0], url = items[1],url = url + ( name === 'tj_m
ap' ? encodeURIComponent('&' + wd + '=' + key) : ( ( url.indexOf('?') > 0 ? '&'
: '?' ) + wd + '=' + encodeURIComponent(key) ) );target.href = url;} else {targe
t.href = target.href.match(new RegExp('^http:\/\/.+\.baidu\.com'))[0];}}name &&
ns_c({'fm': 'behs','tab': name,'query': encodeURIComponent(key),'un': encodeURIC
omponent(bds.comm.user || '') });};}})();};if(window.pageState==0){initIndex();}
})();document.cookie = 'IS_STATIC=1;expires=' + new Date(new Date().getTime() +
10*60*1000).toGMTString();</script>
</body></html>

D:\nodejs>

这个是在dos上接下来的文字,里面很明确的,是百度的文本,所以就不多说,毕竟就是这么个硬道理放在这儿

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值