Skip to content

Commit 95d45d7

Browse files
marzelinjasnell
authored andcommitted
doc: improved example for http.get
PR-URL: #9065 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Luigi Pinca <[email protected]>
1 parent 06f3747 commit 95d45d7

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
@@ -1437,16 +1437,47 @@ added: v0.3.6
14371437
* Returns: {http.ClientRequest}
14381438

14391439
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.
14421444

1443-
Example:
1445+
The `callback` is invoked with a single argument that is an instance of
1446+
[`http.IncomingMessage`][]
1447+
1448+
JSON Fetching Example:
14441449

14451450
```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+
});
14501481
}).on('error', (e) => {
14511482
console.log(`Got error: ${e.message}`);
14521483
});

0 commit comments

Comments
 (0)