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