Extracting information and converting it into JSON format using Express

I am currently extracting data from a website and attempting to display it in the browser as JSON. However, although I can see the data when using console.log() on the recipes array, nothing is being sent to the browser. Why is the JSON array not showing up in the browser?

router.get('/scrape', function(req, res, next) {

  res.json(scrapeUrl("http://url"));

})

function scrapeUrl(url) {
  request(url, function(error, response, html){

    // First we'll check to make sure no errors occurred when making the request
    if(!error){

      var $ = cheerio.load(html);
      var recipes = [];



      $('div.article-block a.picture').each(function(i, elem) {

        var deepUrl = $(this).attr('href');

        if(!$(this).attr('href').indexOf("tema") > -1) {
          request(deepUrl, function(error, response, html){

            // First we'll check to make sure no errors occurred when making the request
            if(!error){


              var $ = cheerio.load(html);

              var image = $('div.article div.article-main-pic img').attr('src');
              var title = $('div.recipe h2.fn').text();

              var object = {url: deepUrl, title : title, image : image};

              recipes.push(object);

            }

          });

        }

      });
      return recipes;
    }
  });
}

Answer №1

Your Scraping Function is asynchronous by nature.

To resolve this, follow the code snippet below:

router.get('/scrape', function(req, res, next) {
  scrapeUrl("http://url", function(err, resp){
     res.json(resp);
  });
});

Add a callback function in your scrapeUrl method like shown:

scrapeUrl (url, cb) {
  request(url, function(error, response, html){
    // Add your remaining code here
    // Ensure to call the callback once all requests are completed.
    cb(err, resp)
  });
}

I hope this solution resolves the issue you are facing.

Answer №2

Your code is simply generating an array without actually displaying it on the webpage.

If you want to showcase the array data in the browser, you should create a designated container for it:

<div id="output"></div>

Then, update your function to output the array within this container:

$('#output').text(JSON.stringify(data));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript code that includes a while loop and an ajax call is malfunctioning

While attempting to create a basic while loop in JavaScript, I keep encountering the spinning wheel icon on my Mac every time I run my script. The code below is triggered by pressing an HTML button: <script type="text/javascript"> $(document).re ...

Tips for preserving textarea content upon clicking outside the area with the help of ajax

I am new to using the Froala editor and I am currently working on a feature where I need to save text in the textarea of the editor when the user clicks outside of it using Ajax. The ID of the content editor is #id_content. Here is a snippet of my form in ...

Chosen option within the AntD Select component

Using the AntD select component, there seems to be an issue where it displays "id" instead of "name" when selecting options. Is there a solution available for this problem? const MyComponent = () => { const data = [ { id: "5c83c2d ...

What is the reason behind certain vanilla JavaScript libraries necessitating NPM?

I am a beginner in JavaScript and I want to learn more about it. Recently, I discovered a library called bounce.js which is an animation library. However, it requires NPM for installation, but I am hesitant to use NPM or any packet Manager because they hav ...

Utilizing nested routes in Node.js with express.js framework!

index.js const AuthRouter = require("./Routes/Auth/signup") app.use("/account", AuthRouter) signup.js router.post("/", async (req, res) => { res.send("Signup") }) It's functioning correctly... H ...

The lightbox fails to display in IE when a synchronous ajax request is triggered

I have a piece of code that displays a lightbox with the message 'Please Wait', followed by a synchronous ajax request that removes the lightbox once it's completed. This setup works perfectly in most browsers, but in Internet Explorer, the ...

Displaying a loading spinner while waiting for the Vue.js app to render

Currently, I am developing a Vue.js application and I'm facing a challenge in adding a loading spinner before the app component is rendered. Instagram has a similar feature where they display their logo before showing the page contents. I have tried v ...

Error in Json_decode displaying incorrectly

Hey, I've been trying to figure this out all day. For some reason, when I try to load JSON remotely it decodes correctly using the following code; $uri = 'http://example.com/json'; $data = file_get_contents($uri); $json = json_decode($data ...

Activate click events when button is being held down

I'm currently working on a directive that shifts an element to the right whenever clicked. However, I want the element to keep moving as long as the button is pressed. .directive("car", function(){ return { restrict:"A", link:func ...

Tool to insert content into the initial subdirectory

My goal is to develop a bookmarklet that can add text after the main domain but before any subpath. For example: http://example.com/home/start -> http://example.com/text/home/start I am considering storing the full path, removing the domain, replacing ...

Creating a PHP table using JSON data without specifying column names in the array

I am struggling with the Yandex API, trying to retrieve data and create a table using PHP: {"data":[ {"dimensions":[{"name":"organic"}],"metrics":[s1v1,s1v2,s1v3,s1v4,s1v5,s1v6]}, {"dimensions":[{"name":"referral"}],"metrics":[s2v1,s2v2,s2v3,s2v4,s2v5,s2v ...

Is there a way to input my Firebase information into Google Sheets?

I have a database stored in Firebase, and my goal is to retrieve the information from there and transfer it into a Google Spreadsheet. function fetchDatabaseData() { var ss = SpreadsheetApp.getActiveSpreadsheet(); var sheet = ss.getSheetByName("Databa ...

There is a misconception about how javascript .map() can alter the original array rather than simply creating a modified version of it

While working on some code, I noticed that the previous person was modifying the original array by reference. I thought that the .map() function in JavaScript works by returning a new copy with the modifications made within the map. The following code dem ...

How can one change the color of movable tiles to red while keeping the rest of the tiles in their original state in a puzzle game?

In this section of our code, the function moveTile is responsible for moving a tile. How can I modify it so that the hover color changes to red? function moveTile(identity) { var emptyId = findEmptySpace(); if (isEmptyNeighbor(identity)) { document.ge ...

Just released a new npm package called vue-izitheme. It's fully functional from the command line, but for some reason it's not showing up in search results. Any suggestions on how to fix

I released my project, vue-izitheme, two days ago but I can't seem to find it when searching. It is functioning correctly from the command line and has already been downloaded 44 times. Do you have any thoughts on what could be causing this issue? ...

Identifying the validity of specific conditions and proceeding with additional actions if confirmed

I'm working on a game for a class assignment and I need help creating a function that can determine whether the main hero character is within a specified boundary. If the hero character is within the bounds, the function should trigger a series of con ...

JQ: Leveraging variables in dot notation paths

Can a variable be used to store a dot notation path? (Apologies if that's not the correct term.) For instance, consider the following JSON: { "people": [ { "names": { "given": "Alice", ...

What is the best way to conceal a div in React using components?

Below is the code I have for my App: import React, {Component} from 'react'; import App1 from './App1'; class App extends Component { render(){ return ( <> <App1/> ...

MVC - transforming a model into a JSON object

In my MVC project, I utilized an Mvc object as my model. My requirement is to stringify my model into a JSON object so that I can use it in JavaScript as needed. Currently, I am implementing something along the lines of: <script type="text/javascript ...

Discovering the optimum route within a 2D array given specific limitations using Dynamic Programming

Hey, I have a query related to dynamic programming (dp) that goes like this: Input: A 2D array of numbers Output: The maximum sum of a path from (0,0) to (n-1,n-1) with the following conditions: You can only move down and right i.e. from (A[i-1][j]) t ...