1创建 客户端client.js 文件:
var http = require('http');
// 用于请求的选项
var options = {
host: 'localhost',
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();
2页面:index.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鸟教程(runoob.com)</title> </head> <body> <h1>我的第一个标题</h1> <p>我的第一个段落。</p> </body> </html>
3服务器server.js:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
// This will serve your request to '/'.
});
app.listen(8080, function () {
console.log('Example app listening on port 8080!');
});
4执行命令:
node server.js
5执行命令:
node client.js
出现: