【问题标题】:How to make web service calls in Expressjs?如何在 Expressjs 中进行 Web 服务调用?
【发布时间】:2011-10-05 10:13:57
【问题描述】:
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调用?

【问题讨论】:

    标签: node.js express


    【解决方案1】:

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

    【讨论】:

    • 更新了最新文档的链接,此页面在 google 搜索结果中的返回率很高。
    • 如果响应足够大,这不会占用内存吗?当你得到它们时将块写回响应不是更好吗?这甚至可能吗?
    • 如果您只是代理请求,那么流式传输将是首选方法。
    • 我正在尝试获取var options = { host: 'en.wikipedia.org', path: '/wiki/United_Kingdom' };,但它给出了空白响应
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 2022-07-03
    相关资源
    最近更新 更多