您的位置:首页 > 理论基础 > 计算机网络

(三)Electron网络访问

2016-03-29 21:58 513 查看
这一章使用Node的http模块加载网络资源。

加载http模块:

var http = require('http');


使用get方法加载url:

http.get('http://www.baidu.com',function(res){});


更多的使用方法请参考Node官方文档

添加data事件读取数据并设置编码:

res.setEncoding('utf8');
res.on('data',function(chunk){
text.textContent += chunk;
});


完整代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>loadfile</title>
</head>
<body>
<p>加载网络资源:</p>
<button id="load">load</button>
<textarea id="text" style="width: 100%;height: 500px;background: #d9e8f0">
</textarea>
</body>
<script>
var fs = require('fs');
var http = require('http');
var text = document.getElementById('text');
var load = document.getElementById('load');
load.addEventListener('click',function(){
loadSomeData();
});

function loadSomeData(){
http.get('http://www.baidu.com',function(res){
res.setEncoding('utf8');
res.on('data',function(chunk){
text.textContent += chunk;
});
});
}
</script>
</html>


结果图:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息