您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Node.js Express中的HTTP GET请求

Node.js Express中的HTTP GET请求

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

请注意,还有更多的最佳方法(仅作为示例)-例如,与其将放入数组的块连接起来并进行连接等,不希望将它们串联在一起。希望,它可以使您朝正确的方向开始:

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

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

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

并提供回调函数

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

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(线性,无回调),promise,编译时支持和智能感知,我们创建了一个符合该要求的轻量级HTTP和REST客户端:

Node 2022/1/1 18:13:44 有539人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶