@@ -1437,16 +1437,47 @@ added: v0.3.6
1437
1437
* Returns: {http.ClientRequest}
1438
1438
1439
1439
Since most requests are GET requests without bodies, Node.js provides this
1440
- convenience method. The only difference between this method and [ ` http.request() ` ] [ ]
1441
- is that it sets the method to GET and calls ` req.end() ` automatically.
1440
+ convenience method. The only difference between this method and
1441
+ [ ` http.request() ` ] [ ] is that it sets the method to GET and calls ` req.end() `
1442
+ automatically. Note that response data must be consumed in the callback
1443
+ for reasons stated in [ ` http.ClientRequest ` ] [ ] section.
1442
1444
1443
- Example:
1445
+ The ` callback ` is invoked with a single argument that is an instance of
1446
+ [ ` http.IncomingMessage ` ] [ ]
1447
+
1448
+ JSON Fetching Example:
1444
1449
1445
1450
``` js
1446
- http .get (' http://www.google.com/index.html' , (res ) => {
1447
- console .log (` Got response: ${ res .statusCode } ` );
1448
- // consume response body
1449
- res .resume ();
1451
+ http .get (' http://nodejs.org/dist/index.json' , (res ) => {
1452
+ const statusCode = res .statusCode ;
1453
+ const contentType = res .headers [' content-type' ];
1454
+
1455
+ let error;
1456
+ if (statusCode !== 200 ) {
1457
+ error = new Error (` Request Failed.\n ` +
1458
+ ` Status Code: ${ statusCode} ` );
1459
+ } else if (! / ^ application\/ json/ .test (contentType)) {
1460
+ error = new Error (` Invalid content-type.\n ` +
1461
+ ` Expected application/json but received ${ contentType} ` );
1462
+ }
1463
+ if (error) {
1464
+ console .log (error .message );
1465
+ // consume response data to free up memory
1466
+ res .resume ();
1467
+ return ;
1468
+ }
1469
+
1470
+ res .setEncoding (' utf8' );
1471
+ let rawData = ' ' ;
1472
+ res .on (' data' , (chunk ) => rawData += chunk);
1473
+ res .on (' end' , () => {
1474
+ try {
1475
+ let parsedData = JSON .parse (rawData);
1476
+ console .log (parsedData);
1477
+ } catch (e) {
1478
+ console .log (e .message );
1479
+ }
1480
+ });
1450
1481
}).on (' error' , (e ) => {
1451
1482
console .log (` Got error: ${ e .message } ` );
1452
1483
});
0 commit comments