使用 Node 创建 Web 客户端
服务端已经开启
代码 client.js
var http = require('http'); // 用于请求的选项 var options = { host: 'http://127.0.0.1', port: '8080', path: 'index.html' }; // 处理响应的回调函数 var callback = function(response){ // 不断更新数据 var body = ''; response.on('data', function(data) { body += data; }); // 数据接收完成 response.on('end', function() { console.log(body); }); } // 向服务端发送请求 var req = http.request(options, callback); // 结束请求 req.end();
运行该js文件报错
少了request
的error handler
,改改吧:
var http = require('http');
// 用于请求的选项
var options = {
protocol: 'http:',
host: '127.0.0.1',
port: '8080',
path: '/index.html'
};
// 处理响应的回调函数
var callback = function(response){
// 不断更新数据
var body = '';
response.on('data', function(data) {
body += data;
});
// 数据接收完成
response.on('end', function() {
console.log(body);
});
}
// 向服务端发送请求
var req = http.request(options, callback);
//处理请求错误
req.on('error', function(e) {
console.log('problem with request: ' + e);
});
// 结束请求
req.end();
看文档:
地址:http