如何在Expressjs中进行Web服务调用? [英] How to make web service calls in Expressjs?

查看:63
本文介绍了如何在Expressjs中进行Web服务调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  app.get('/',function(req,res){

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

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


任何人都知道为什么?或如何进行http呼叫?

解决方案

查看示例 here 在node.js文档。



方法 http.get 是一种方便的方法,它处理了GET请求的大量基本内容,通常它没有任何机构。以下是如何制作简单的HTTP GET请求的示例。

  var http = require(http); 

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

http.get(options,function(http_res){
//初始化我们的数据的容器
var data =;

/ /这个事件多次发生,每次收集另一段响应
http_res.on(data,function(chunk){
//将这个块附加到我们不断增长的datavar
data + = chunk;
});

//此事件触发*一个*时间,所有的`data`事件/块已经被收集
http_res。 on(end,function(){
//你可以使用res.send而不是console.log通过express
console.log(data);
});
});


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

});

I am trying to download google.com homepage, and reprint it, but I get an "Can't use mutable header APIs after sent." error

Anyone know why? or how to make http call?

解决方案

Check out the example here on the node.js doc.

The method http.get is a convenience method, it handles a lot of basic stuff for a GET request, which usually has no body to it. Below is a sample of how to make a simple HTTP GET request.

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

这篇关于如何在Expressjs中进行Web服务调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆