2011-07-14 18 views
8
app.get('/', function(req, res){ 

var options = { 
    host: 'www.google.com' 
}; 

http.get(options, function(http_res) { 
    http_res.on('data', function (chunk) { 
     res.send('BODY: ' + chunk); 
    }); 
    res.end(""); 
}); 

});如何在Expressjs中進行Web服務調用?

我想下載google.com主頁,並重新打印它,但是我收到了「發送後無法使用可變頭文件API」。錯誤

任何人都知道爲什麼?或如何使http呼叫?

回答

33

查看node.js文檔中的示例here

方法http.get是一種方便的方法,它爲GET請求處理了很多基本的東西,它通常沒有任何內容。以下是如何製作簡單的HTTP GET請求的示例。

var http = require("http"); 

var options = { 
    host: 'www.google.com' 
}; 

http.get(options, function (http_res) { 
    // initialize the container for our data 
    var data = ""; 

    // this event fires many times, each time collecting another piece of the response 
    http_res.on("data", function (chunk) { 
     // append this chunk to our growing `data` var 
     data += chunk; 
    }); 

    // this event fires *one* time, after all the `data` events/chunks have been gathered 
    http_res.on("end", function() { 
     // you can use res.send instead of console.log to output via express 
     console.log(data); 
    }); 
}); 
+0

更新後的最新文檔鏈接,此頁面在谷歌搜索結果中返回高位。 – blu

+0

如果響應足夠大,會不會消耗內存?當你得到它們時,把這些塊寫回響應是不是更好?這甚至有可能嗎? – chovy

+1

如果您只是代理請求,那麼yes流將是首選方法。 –