如何在Expressjs中进行Web服务调用?

12
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("");
});

});

我试图下载google.com首页,并将其重印出来,但是我遇到了一个“无法在发送后使用可变标头API”的错误。

有人知道原因吗?或者如何进行http调用?

1个回答

38

请看node.js文档中此处的示例。

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);
    });
});

更新最新文档链接,该页面在谷歌搜索结果中排名较高。 - blu
如果响应足够大,这样做不会占用太多内存吗?把块写回响应中是否更好?这样做可能吗? - chovy
1
如果您只是代理请求,那么流式传输将是首选方法。 - Dominic Barnes
我正在尝试获取以下代码:var options = { host: 'en.wikipedia.org', path: '/wiki/United_Kingdom' };但是它返回空响应。 - mujaffars

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接