I am currently building an web service using an external API and crawling data using Cheerio. I was able to get the data from Cheerio and trying to push a new variable from the crawl to the item data (article). I've tried item.push({"new content":new content here});, as well as return (variable name), but I am unable to append the new variable to the field image_url. I have no problems with Cheerio and the output of the overall service.
How would go about appending the content variable?
request("<API URL HERE>", function(error, response, body) {
 var myObject = JSON.parse(body);
 var listing = myObject.items; 
 arr = listing.map(function(item) { 
   var url = item.url;
   //get individual images for articles based on URL
   update =  request(url, function (error, response, body) {
       if (!error) {
         var $ = cheerio.load(body) 
         content = $('.post-body').find('img').attr('src');
         return content; 
      }
      else {
        console.log("We’ve encountered an error: " + error);
      }
   });
   //return format for each article 
   return { 
      "title": item.title, 
      "subtitle": item.content.substr(0,100), 
      "image_url": update.content,
       "buttons":
          [{
              "type":"web_url",
              "url":item.url,
              "title":"View Item"
            }]
     };
 });
 res.send({
  "messages": [
   {
     "attachment":{
     "type":"template",
     "payload":{
       "template_type":"generic",
       "elements": arr
      }
   }
  }
 ]
 })
});
via Jeffrey Teruel
No comments:
Post a Comment