0

Js code i can't understand

console.log('This is my tutorial 42'); // Button with id myBtn let myBtn = document.getElementById("myBtn"); // div with id content let content = document.getElementById("content"); function getData(){ console.log("Started getData") url = "https://api.github.com/users"; fetch(url).then((response)=>{ console.log("Inside first then") return response.json(); }).then((data)=>{ console.log("Inside second then") console.log(data); }) } function postData(){ url = "http://dummy.restapiexample.com/api/v1/create"; data = '{"name":"harglry347485945","salary":"123","age":"23"}' params = { method:'post', headers: { 'Content-Type': 'application/json' }, body: data } fetch(url, params).then(response=> response.json()) .then(data => console.log(data) ) } // console.log("Before running getData") // getData() // console.log("After running getData") postData()

7th Sep 2022, 6:29 AM
Abhishek
Abhishek - avatar
6 odpowiedzi
+ 3
What is it that you don't understand?
7th Sep 2022, 6:36 AM
Mustafa A
Mustafa A - avatar
+ 1
you are accessing an api. Learn about the fetch function and json parsing, as well as object destructuring.
7th Sep 2022, 7:34 AM
Bob_Li
Bob_Li - avatar
+ 1
in the function getData(), you passed the url "https://api/github.com/users" to the fetch function. This returns a response promise that you handle inside the. then() method. you pass the response object to an arrow function that parses it (response.json()). response.json() converts response to a json object promise. https://developer.mozilla.org/en-US/docs/Web/API/Response/json Another .then method afterwards further processes the response by passing the extracted data to another arrow function, this time a console.log(data). You should examine the structure of the json object you get. I think it is more useful if you used console.log(Object.entries(data))
7th Sep 2022, 9:32 AM
Bob_Li
Bob_Li - avatar
0
I don't understand that the promise which is fetch (url . then and arrow method
7th Sep 2022, 9:02 AM
Abhishek
Abhishek - avatar
0
response.json
7th Sep 2022, 9:02 AM
Abhishek
Abhishek - avatar
0
abhishek bairwa I think it is wrong to use response.json() here because your url "https://api/github.com/users" is pointing to an html file. The json is embedded in a pre tag. maybe replace response.json() with response.text()
7th Sep 2022, 12:20 PM
Bob_Li
Bob_Li - avatar