【问题标题】:Trying to return JSON object from Express and Node app. Getting a blank object尝试从 Express 和 Node 应用程序返回 JSON 对象。获取空白对象
【发布时间】:2019-02-27 11:01:54
【问题描述】:

请帮帮我,我觉得 res.json() 有点像。如果我在第一个请求之后调用它,它会起作用,但不是第二个。实际的应用程序现在非常基础,它只是从 twitter 或 instagram 等社交媒体上抓取一些用户数据,然后返回 json 对象。谢谢!

app.get("/", function(req, res) {
  let twitterHandle = req.query.twitter;
  let instagramHandle = req.query.instagram;

  let twitterURL = "https://twitter.com/" + twitterHandle + "?lang=en";
  let instagramURL = "https://instagram.com/" + instagramHandle;

  var json = {};

  console.log(twitterHandle);
  console.log(instagramHandle);

  // The structure of our request call
  // The first parameter is our URL
  // The callback function takes 3 parameters, an error, response status code and the html
  if (twitterHandle != "") {
    request(twitterURL, function(error, response, html) {
      // First we'll check to make sure no errors occurred when making the request
      if (!error) {
        // Next, we'll utilize the cheerio library on the returned html which will essentially give us jQuery functionality
        var $ = cheerio.load(html);

        // Finally, we'll define the variable we're going to capture
        // We'll be using Cheerio's function to single out the necessary information
        // using DOM selectors which are normally found in CSS.
        var twitterFollowers = $(
          "#page-container > div.ProfileCanopy.ProfileCanopy--withNav.ProfileCanopy--large.js-variableHeightTopBar > div > div.ProfileCanopy-navBar.u-boxShadow > div.AppContainer > div > div.Grid-cell.u-size2of3.u-lg-size3of4 > div > div > ul > li.ProfileNav-item.ProfileNav-item--followers > a"
        )
          .text()
          .replace(/\D/g, "");

        var twitterFollowing = $(
          "#page-container > div.ProfileCanopy.ProfileCanopy--withNav.ProfileCanopy--large.js-variableHeightTopBar > div > div.ProfileCanopy-navBar.u-boxShadow > div.AppContainer > div > div.Grid-cell.u-size2of3.u-lg-size3of4 > div > div > ul > li.ProfileNav-item.ProfileNav-item--following > a"
        )
          .text()
          .replace(/\D/g, "");

        // And now, the JSON format we are going to expose

        json[twitterFollowers] = twitterFollowers;
        json[twitterFollowing] = twitterFollowing;

        // Send the JSON as a response to the client
      }
    });
  }
  if (instagramHandle != "") {
    request(instagramURL, function(error, response, html) {
      // First we'll check to make sure no errors occurred when making the request
      if (!error) {
        // Next, we'll utilize the cheerio library on the returned html which will essentially give us jQuery functionality
        var $ = cheerio.load(html);

        // Finally, we'll define the variable we're going to capture
        // We'll be using Cheerio's function to single out the necessary information
        // using DOM selectors which are normally found in CSS.
        var instagramFollowers = "chicken";

        var instagramFollowing = "chicken";

        // And now, the JSON format we are going to expose
        json.instagramFollowers = instagramFollowers;
        json.instagramFollowing = instagramFollowing;

        // Send the JSON as a response to the client
      }
    });
  }
  res.json(json);
});
app.listen(process.env.PORT || 3000);
module.exports = app;

【问题讨论】:

  • request() 之类的调用是异步的,因此您在填充 res.json(json) 之前会返回它。
  • 我明白你在说什么,我现在正在玩 res.json()。你觉得把它放在哪里最好?我认为把它放在我拥有的地方是最好的,因为我提出请求,存储数据,然后返回对象。
  • 把它放在一个函数中,然后从两个 request()s 的回调中调用该函数,上面写着“发送 JSON”。

标签: javascript html node.js http express


【解决方案1】:

Javascript 是异步的,因此您在收到带有对request() 的调用结果的回调之前发送响应。您需要通过res.json() 或调用另一个函数从回调中发送请求。

// get the request here
app.get("/", function(req, res) {
  // do some stuff
  if (foo) {
    // make a request
    request(url1, function(err, res, html) {
      // get the callback with the result
      const json = { foo: 'bar' };

      // call the function to send the response inside the callback
      return res.json(json);
    });
  }
  // don't send response here since it will get called before the callback
  // even though it is further down in the code since it's asynchronous.
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 2018-12-16
    • 1970-01-01
    相关资源
    最近更新 更多