-
Notifications
You must be signed in to change notification settings - Fork 0
/
7.fetch_from_api.js
56 lines (47 loc) · 1.62 KB
/
7.fetch_from_api.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/*
* An example of fetching data from an online API using only the built-in https module.
* Note that there are 3rd-party modules for node that make this easier.
*
* The mock API used here returns an array of product objects, in the following format:
* [
* {
* id: 1,
* title: 'Boa, emerald green tree',
* country: 'Russia',
* price: '$31.82',
* description: 'Sed ante. Vivamus tortor. Duis mattis egestas metus.'
* },
* {
* id: 2,
* title: 'Bleu, blue-breasted cordon',
* country: 'Ethiopia',
* price: '$35.66',
* description: 'Praesent blandit. Nam nulla. Integer pede justo, lacinia eget, tincidunt eget, tempus vel, pede.'
* },
* ...
* ]
*
*/
// we will use node's built-in https module to make requests over the internet
const https = require('https');
// the URL of a mock API of products for demonstration purposes
const apiUrl = "https://my.api.mockaroo.com/users.json?key=d9ddfc40"
https.get(apiUrl, (response) => {
let data = ''; // this will hold the data received from the server's response
// A chunk of data has been recieved.
response.on('data', (chunk) => {
data += chunk;
});
// The whole response has been received. Print out the result.
response.on('end', () => {
let products = JSON.parse(data); // convert string to object
console.log( products ); // output the raw data
// loop through each product
products.map( (product) => {
// print the title and price of each product
console.log(`${product.title} - ${product.price}`)
});
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});