首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Node.js Express中的HTTP GET请求

Node.js Express中的HTTP GET请求
EN

Stack Overflow用户
提问于 2012-03-06 11:43:20
回答 11查看 531K关注 0票数 216

如何在Node.js或Express.js中发出HTTP请求?我需要连接到其他服务。我希望调用是异步的,并且回调包含远程服务器的响应。

EN

回答 11

Stack Overflow用户

回答已采纳

发布于 2012-03-06 11:50:52

下面是我的一个示例中的一些代码片段。它是异步的,并返回一个JSON对象。它可以执行任何形式的GET请求。

请注意,还有更多的优化方法(只是一个示例)-例如,不是将放入数组中的块连接到一个数组中,等等……希望它能让你朝着正确的方向开始:

代码语言:javascript
复制
const http = require('http');
const https = require('https');

/**
 * getJSON:  RESTful GET request returning JSON object(s)
 * @param options: http options object
 * @param callback: callback to pass the results JSON object(s) back
 */

module.exports.getJSON = (options, onResult) => {
  console.log('rest::getJSON');
  const port = options.port == 443 ? https : http;

  let output = '';

  const req = port.request(options, (res) => {
    console.log(`${options.host} : ${res.statusCode}`);
    res.setEncoding('utf8');

    res.on('data', (chunk) => {
      output += chunk;
    });

    res.on('end', () => {
      let obj = JSON.parse(output);

      onResult(res.statusCode, obj);
    });
  });

  req.on('error', (err) => {
    // res.send('error: ' + err.message);
  });

  req.end();
};

它是通过创建一个选项对象来调用的,如下所示:

代码语言:javascript
复制
const options = {
  host: 'somesite.com',
  port: 443,
  path: '/some/path',
  method: 'GET',
  headers: {
    'Content-Type': 'application/json'
  }
};

并提供回调函数。

例如,在服务中,我需要上面的REST模块,然后执行以下操作:

代码语言:javascript
复制
rest.getJSON(options, (statusCode, result) => {
  // I could work with the resulting HTML/JSON here. I could also just return it
  console.log(`onResult: (${statusCode})\n\n${JSON.stringify(result)}`);

  res.statusCode = statusCode;

  res.send(result);
});

更新

如果你正在寻找async/await (线性,无回调),promises,编译时支持和智能感知,我们创建了一个轻量级的HTTP和REST客户端来满足这个要求:

Microsoft typed-rest-client

票数 237
EN

Stack Overflow用户

发布于 2012-03-06 13:32:48

尝试在node.js中使用简单的http.get(options, callback) function

代码语言:javascript
复制
var http = require('http');
var options = {
  host: 'www.google.com',
  path: '/index.html'
};

var req = http.get(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));

  // Buffer the body entirely for processing as a whole.
  var bodyChunks = [];
  res.on('data', function(chunk) {
    // You can process streamed parts here...
    bodyChunks.push(chunk);
  }).on('end', function() {
    var body = Buffer.concat(bodyChunks);
    console.log('BODY: ' + body);
    // ...and/or process the entire body here.
  })
});

req.on('error', function(e) {
  console.log('ERROR: ' + e.message);
});

还有一个通用的http.request(options, callback) function,允许您指定请求方法和其他请求详细信息。

票数 105
EN

Stack Overflow用户

发布于 2013-08-04 02:50:14

你也可以使用Requestify,这是我为nodeJS +编写的一个非常酷而且非常简单的客户端,它支持缓存。

对于GET方法请求,只需执行以下操作:

代码语言:javascript
复制
var requestify = require('requestify');

requestify.get('http://example.com/api/resource')
  .then(function(response) {
      // Get the response body (JSON parsed or jQuery object for XMLs)
      response.getBody();
  }
);
票数 35
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9577611

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档