https请求不工作节点js

时间:2018-01-13 08:21:31

标签: javascript node.js api get

我正在开发一个小项目,向API发出请求并获取数据,但编译器没有输入请求。

这是我的代码:

const https = require("https");
function getUserData(username) {
  let error = "";
  let json_data = {};
  try {
    const req = 
       https.get(`https://xteamtreehouse.com/${username}.json`, res => {
     let data = "";
  if (res.statusCode == 200) {
    res.on("data", in_data => {
      data = in_data.toString();
    });
    res.on("end", () => {
      json_data = data;
    });
  } else {
    error = `An ${res.statusCode} error occured!`;
  }
   });
    req.on("error", e => {
      error = e.message;
    })
  } catch (e) {
    error = e.message;
  }
  if (error)
    return false;
  return json_data;
}
console.log(typeof getUserData("chalkers"))

输出:     当我运行该代码时,它没有显示" string"而是显示"对象"这意味着获取请求无效请求帮助。

1 个答案:

答案 0 :(得分:0)

我认为您可能需要一些JavaScript基础知识。

const https = require("https");

// this function returns nothing
function getUserData(username) {

  let rawData = '';

  // this request is asynchronous
  https.get(`https://teamtreehouse.com/${username}.json`, (res) => {
    res.on('data', (d) => {
      console.log('hi data transfering');
      rawData += d;
    });
    res.on('end', (d) => {
      console.log('hi end transfered');

      // now deal with the data
      try {

        // the rawData is a string
        console.log('-------------- cut -----------');
        console.log(typeof rawData);
        console.log('-------------- cut -----------');

        // parse it
        const parsedData = JSON.parse(rawData);
        console.log(parsedData);

      } catch (e) {

        // catch the parsing error
        console.error(e.message);
      }

    });
  }).on('error', (e) => {

    // this is the request error
    console.error(e);
  });
}

// run it
getUserData('chalkers')