http.get(options, callback)
由於該方法屬於http模塊,使用前需要引入http模塊(var http= require(“http”) )
接收參數:
option 數組對象,包含以下參數:
host: 表示請求網站的域名或IP地址(請求的地址)。 默認為'localhost'。
hostname: 服務器名稱,主機名是首選的值。
port: 請求網站的端口,默認為 80。
localAddress: 建立網絡連接的本地
socketPath: Unix Domain Socket(Domain套接字路徑)
method: HTTP請求方法,默認是 ‘GET'。
path: 請求的相對於根的路徑,默認是'/'。QueryString應該包含在其中。例如:/index.html?page=12
headers: 請求頭對象。
auth: Basic認證(基本身份驗證),這個值將被計算成請求頭中的 Authorization 部分。
callback : 回調,傳遞一個參數,為 http.ClientResponse的實例。http.request 返回一個 http.ClientRequest 的實例。
var options = { hostname: 'www.google.com', port: 80, path: '/upload', method: 'POST' }; 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('BODY: ' + chunk); }); }); req.on('error', function(e) { console.log('problem with request: ' + e.message); }); // write data to request body req.write('data\n'); req.write('data\n'); req.end();