作者:喵喵方小幺 | 来源:互联网 | 2023-05-18 08:04
这一章使用Node的http模块加载网络资源。加载http模块:varhttprequire(http);使用get方法加载url:http.get(http:www
这一章使用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));
完整代码:
<html>
<head>
<meta charset="UTF-8">
<title>loadfiletitle>
head>
<body>
<p>加载网络资源:p>
<button id="load">loadbutton>
<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>
结果图:
![](https://www.#.com/go/aHR0cDovL2ltZy5ibG9nLmNzZG4ubmV0LzIwMTYwMzI5MjE1NjI1Njc5)