Node.js Express 中的 HTTP GET 请求 [英] HTTP GET Request in Node.js Express

查看:30
本文介绍了Node.js Express 中的 HTTP GET 请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I make an HTTP request from within Node.js or Express.js? I need to connect to another service. I am hoping the call is asynchronous and that the callback contains the remote server's response.

推荐答案

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

Here is a snippet of some code from a sample of mine. It's asynchronous and returns a JSON object. It can do any form of GET request.

请注意,有更多最佳方法(只是一个示例)-例如,不是将您放入数组中的块连接起来并加入等等...希望它能让您朝着正确的方向开始:

Note that there are more optimal ways (just a sample) - for example, instead of concatenating the chunks you put into an array and join it etc... Hopefully, it gets you started in the right direction:

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

通过创建一个选项对象来调用它,例如:

It's called by creating an options object like:

const options = {
  host: 'somesite.com',
  port: 443,
  path: '/some/path',
  method: 'GET',
  headers: {
    'Content-Type': 'application/json'
  }
};

并提供回调函数.

例如,在一个服务中,我需要上面的 REST 模块,然后这样做:

For example, in a service, I require the REST module above and then do this:

rest.getJSON(options, (statusCode, result) => {
  // I could work with the resulting HTML/JSON here. I could also just return it
  console.log(`onResult: (${statusCode})

${JSON.stringify(result)}`);

  res.statusCode = statusCode;

  res.send(result);
});

更新

如果您正在寻找 async/await(线性,无回调)、promise、编译时支持和智能感知,我们创建了一个轻量级的 HTTP 和 REST 客户端符合该法案:

UPDATE

If you're looking for async/await (linear, no callback), promises, compile time support and intellisense, we created a lightweight HTTP and REST client that fits that bill:

微软 typed-rest-client

这篇关于Node.js Express 中的 HTTP GET 请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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