-1

I have a code that takes the JSON of a webpage (from a link) and prints it into the console with a promise, using node-fetch (npm node-fetch) and .then

I need to get the content of this specific webpage to work with that content for a project I have, but I cannot see any solution on how to really use it

I have this code:

fetch('https://api.faceit.com/core/v1/nicknames/'+req.query.nickname)
        .then(res => res.text())
        .then(body => console.log("json -> "+body))

req.query.nickname is a text variable taken from a form that will serve for the link I use to print the JSON

now, when I get to .then(body => console.log("json -> "+body)) it correctly prints me the JSON but I have no clue on how to use the body that I print

Now, after all this, I have 2 questions

  • how can I used the "body" variable to work with the data I get out of that link?
  • is there any different way (better or not) to get the content from a page, stored into a variable or an Object, that I can work with?

thanks for everyone for the help in advance. If you need an example of the JSON I need to work with, you can use this https://api.faceit.com/core/v1/nicknames/noxter

noxter
  • 186
  • 1
  • 11
  • Yes and now, it does make it more clear than what to do and what no, but in the solutions part it just prints the thing it needs to print I need to use it, not to print it. This is my issue, still thanks for sharing that thread, made many things clear – noxter Jul 11 '21 at 13:29
  • Then just replace the `console.log` with whatever it is you need to actually do? It's only in there that you have access to `body`. Note I'm not suggesting that you write your entire program inside the `.then` callback - but it would be normal to write a function which takes `body` as the argument, then just call it from the `.then`. – Robin Zigmond Jul 11 '21 at 13:39
  • I've done it and it works, super happy you helped, thanks a lot! – noxter Jul 11 '21 at 14:13

1 Answers1

1

Use res.json() instead of res.text() to get the data as an object instead of a string.

Then you can use DOM methods to update the page as usual.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I got into there, nice, now I am trying to get into how to use the DOM on Node, because is a runtime - and it says `ReferenceError: document is not defined` when I am trying to use the DOM – noxter Jul 11 '21 at 13:35
  • Oh. Missed that you are using Node.js. You'll want to use a template engine and not DOM then. https://expressjs.com/en/guide/using-template-engines.html if you are using Express (which you almost certainly should be) – Quentin Jul 11 '21 at 13:36
  • Would this create any conflict if I am using ejs instead of pug? – noxter Jul 11 '21 at 13:40
  • If you've using EJS use EJS. Don't mix and match template engines. – Quentin Jul 11 '21 at 13:41
  • I've done it and it works, glad you helped me and you spent time doing so, thank you so very much – noxter Jul 11 '21 at 14:13