Skip to content

Commit 2c5b27a

Browse files
marzelinMyles Borins
authored and
Myles Borins
committed
doc: improved example for http.get
PR-URL: #9065 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Luigi Pinca <[email protected]>
1 parent de2f050 commit 2c5b27a

File tree

1 file changed

+38
-7
lines changed

1 file changed

+38
-7
lines changed

doc/api/http.md

+38-7
Original file line numberDiff line numberDiff line change
@@ -1448,16 +1448,47 @@ added: v0.3.6
14481448
* Returns: {http.ClientRequest}
14491449

14501450
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.
14531455

1454-
Example:
1456+
The `callback` is invoked with a single argument that is an instance of
1457+
[`http.IncomingMessage`][]
1458+
1459+
JSON Fetching Example:
14551460

14561461
```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+
});
14611492
}).on('error', (e) => {
14621493
console.log(`Got error: ${e.message}`);
14631494
});

0 commit comments

Comments
 (0)