1

I have a REST API of Reddit. I am trying to parse the JSON output to get the URL of the responses. When I try to send the request, I get multiple outputs, but I am not sure how to do it as it's a random response.

https
  .get("https://www.reddit.com/r/cute/random.json", resp => {
    let data = "";

    resp.on("data", chunk => {
      data += chunk;
    });

    const obj = JSON.parse(data);
    resp.on("end", () => {
      console.log(obj.url);
    });
  })
  .on("error", err => {
    console.log("Error: " + err.message);
  });

This is the code I have got. I used the default Node's http library and I don't think it worked. I have never used any Node Libraries, so it will be helpful if you can suggest them too. And also let me know if what I have done is right.

8
  • Any reason why you want to use https library and not something like node-fetch? I have a node-fetch example, I can share with you. Commented Jun 3, 2021 at 8:15
  • @PraveenKumarPurushothaman I am completely new to Node JS, so I am not sure what to use. I just followed some blog post to get it. Commented Jun 3, 2021 at 8:17
  • @PraveenKumarPurushothaman Yea, I am happy with using node-fetch. As long as I get the URL from the JSON response, that's all it matters. Commented Jun 3, 2021 at 8:18
  • you could try axios library. it's well documented and has wide support Commented Jun 3, 2021 at 8:25
  • 1
    @ChrisIhure I checked it, but isn't it just for front end as Praveen says? I had the same question. Commented Jun 3, 2021 at 8:27

1 Answer 1

1

I understand that http is a core library of Node JS, but I strongly suggest you to use something like node-fetch. Make sure you run the following command on your terminal (or cmd) where your package.json file exists:

$ npm install node-fetch

This will install the node-fetch library, which acts similarly to how the Web based fetch works.

const fetch = require("node-fetch");
const main = async () => {
  const json = await fetch("https://www.reddit.com/r/cute/random.json").then(
    res => res.json()
  );
  console.log(
    json
      .map(entry => entry.data.children.map(child => child.data.url))
      .flat()
      .filter(Boolean)
  );
};
main();

The URLs that you are looking for, I could find in the data.children[0].data.url so I did a map there. I hope this is something that might help you.

I get multiple output for the same code, run multiple times, because the URL you have used is a Random Article Fetching URL. From their wiki:

/r/random takes you to a random subreddit. You can find a link to /r/random in the header above. Reddit gold members have access to /r/myrandom, which is right next to the random button. Myrandom takes you to any of your subscribed subreddits randomly. /r/randnsfw takes you to a random NSFW (over 18) subreddit.

The output for me is like this:

[ 'https://i.redd.it/pjom447yp8271.jpg' ]   // First run
[ 'https://i.redd.it/h9b00p6y4g271.jpg' ]   // Second run
[ 'https://v.redd.it/lcejh8z6zp271' ]       // Third run

Since it has only one URL, I changed the code to get the first one:

const fetch = require("node-fetch");
const main = async () => {
  const json = await fetch("https://www.reddit.com/r/cute/random.json").then(
    res => res.json()
  );
  console.log(
    json
      .map(entry => entry.data.children.map(child => child.data.url))
      .flat()
      .filter(Boolean)[0]
  );
};
main();

Now it gives me:

'https://i.redd.it/pjom447yp8271.jpg'   // First run
'https://i.redd.it/h9b00p6y4g271.jpg'   // Second run
'https://v.redd.it/lcejh8z6zp271'       // Third run
'https://i.redd.it/b46rf6zben171.jpg'   // Fourth run

Preview

preview

I hope this helps you. Feel free to ask me if you need more help. Other alternatives include axios, but I am not sure if this can be used on backend.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, this looks very detailed. Let me check and tell you if it works.
@LBGUser Does it work? Lemme know, thanks.
Thanks, this works, this is indeed perfect.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.