HTTPS GET请求的使用结果[Node.js] [英] Use result of HTTPS GET request [Node.js]

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

问题描述

我认为我遇到了一个小问题,但是我找不到解决方法. 我想使用Node.js HTTPS GET请求在变量中加载远程JSON.这是成功的,但是我无法在代码中的其他任何地方使用它.我的功能如下(来自Node.js文档):

I'm stuck with a small problem I think, but I can't find a way to solve it. I want to load a remote JSON in a variable, using Node.js HTTPS GET request. It's a success, but I can't use it anywhere else in my code. My function is the following (from Node.js doc):

function getMyFile() {
  var https = require('https');

  https.get('URL_I_am_targeting/file.json', (res) => {
    var { statusCode } = res;
    var contentType = res.headers['content-type'];

    let error;

    if (statusCode !== 200) {
      error = new Error('Request Failed.\n' +
                        `Status Code: ${statusCode}`);
    } else if (!/^application\/json/.test(contentType)) {
      error = new Error('Invalid content-type.\n' +
                        `Expected application/json but received ${contentType}`);
    }

    if (error) {
      console.error(error.message);
      // consume response data to free up memory
      res.resume();
    }

    res.setEncoding('utf8');
    let rawData = '';

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

    res.on('end', () => {
      try {
        const parsedData = JSON.parse(rawData);
        console.log(parsedData);
      } catch (e) {
        console.error(e.message);
      }
    });
  }).on('error', (e) => {
    console.error(`Got error: ${e.message}`);
  });
}

该请求工作正常,因为我能够在控制台中正确记录我的.json.但是我的问题是我无法在代码的其他任何地方使用常量"parsedData".我试图写我的

The request works fine, as I am able to log my .json in the console correctly. But my problem is that I can't use the constant "parsedData" anywhere else in my code. I tried to write my

return parsedData;

在函数中的多个位置,但是当我在代码中使用该函数并尝试f时. e.

at several places in my function, but when I use the function in my code and try f. e.

var fileContent = getMyFile();
console.log(fileContent);

fileContent未定义.就像parsedData不能超出请求一样.没有记录错误,请求可以正常进行,但是我无法使用其中的内容.

fileContent is undefined. It's like parsedData can't go out of the request. There is no error logged, the request goes fine, but I just can't use the content out of it.

我不是Java语言专业人士,从此请求中返回值可能是我的错.

I am not a Javascript professional, and it's probably something I get wrong with returning value from this request.

如果有人知道我错了哪里以及可以解决的方法,将不胜感激! 谢谢!

If somebody knows where I'm wrong and what could do the trick, it will be greatly appreciated ! Thanks !

推荐答案

您可以为函数编写基于诺言的包装器:

You could write a promise-based wrapper for your function:

function getMyFile() {
  var https = require('https');

  return new Promise((resolve, reject) => {
      https.get('URL_I_am_targeting/file.json', (res) => {
        var { statusCode } = res;
        var contentType = res.headers['content-type'];

        let error;

        if (statusCode !== 200) {
          error = new Error('Request Failed.\n' +
            `Status Code: ${statusCode}`);
        } else if (!/^application\/json/.test(contentType)) {
          error = new Error('Invalid content-type.\n' +
            `Expected application/json but received ${contentType}`);
        }

        if (error) {
          console.error(error.message);
          // consume response data to free up memory
          res.resume();
        }

        res.setEncoding('utf8');
        let rawData = '';

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

        res.on('end', () => {
          try {
            const parsedData = JSON.parse(rawData);
            resolve(parsedData);
          } catch (e) {
            reject(e.message);
          }
        });
      }).on('error', (e) => {
        reject(`Got error: ${e.message}`);
      });

    });
  }

因此,您可以使用如下功能:

So that, you can use the function like this:

getMyFile()
  .then(response => {
    // handle success response here
  })
  .catch(error => {
    // handle error here
  });

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

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