node.js - 如何在 Expressjs 中进行 Web 服务调用?

标签 node.js express

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 主页并重新打印,但我收到“发送后无法使用可变 header API”。错误

有人知道为什么吗?或者如何进行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) {
    // 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);
    });
});

关于node.js - 如何在 Expressjs 中进行 Web 服务调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6695143/

相关文章:

javascript - nodejs xhr POST

javascript - 保存并填充 Node js

node.js - NodeJS 数据库迁移类型错误 : Cannot read property '1' of null

node.js - 如何在 Node.js 上的 Express.js 中获取 GET(查询字符串)变量?

javascript - EJS 和 Mongoosse 中的 .forEach()

node.js - Web3 + 坚固性 : Passing in arguments to a contract's constructor

node.js - 更新 MongoDb 子文档中数组中的特定文档

javascript - POST 请求未填充正文

javascript - 如何在express js中将数组值发送到html页面

javascript - 嵌套的 forEach 循环存在异步问题,每次以不同的速率完成