http 客戶端
http 客戶端的基本示例:
在 http_client.js 檔案中寫下以下程式碼:
var http = require('http');
var options = {
hostname: '127.0.0.1',
port: 80,
path: '/',
method: 'GET'
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('Response: ' + chunk);
});
res.on('end', function (chunk) {
console.log('Response ENDED');
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
req.end();
然後從你的 http_client.js 位置執行此命令:
node http_client.js
你應該看到這個結果:
> STATUS: 200
> HEADERS: {"content-type":"text/plain","date":"Thu, 21 Jul 2016 11:27:17 GMT","connection":"close","transfer-encoding":"chunked"}
> Response: OK
> Response ENDED
注意:此示例依賴於 http 伺服器示例。