owned this note
owned this note
Published
Linked with GitHub
## Making HTTP requests with Node.js (using callbacks)
### 1. HTTP module
**Pros**:
1. native/built in module, there is no need to install third party modules
**Cons**:
1. the response is a stream --> data needs to be collected in chuncks, manipulation needed to extract the JSON response.
2. a bit verbose
3. no support for promises
```
const https = require("https");
const url =
"[https://maps.googleapis.com/maps/api/geocode/json?address=Florence](https://maps.googleapis.com/maps/api/geocode/json?address=Florence)";
https.get(url, res => {
res.setEncoding("utf8");
let body = "";
res.on("data", data => {
body += data;
});
res.on("end", () => {
body = JSON.parse(body);
console.log(
\`City: ${body.results\[0\].formatted_address} -\`,
\`Latitude: ${body.results\[0\].geometry.location.lat} -\`,
\`Longitude: ${body.results\[0\].geometry.location.lng}\`
);
});
});
```
### 1. Request module
**Pros**:
1. easier to use
**Cons**:
1. it’s a third party module with many dependencies (22)
To install the module, run `npm i request` inside your terminal.
```
const request = require("request");
const url =
"[https://maps.googleapis.com/maps/api/geocode/json?address=Florence](https://maps.googleapis.com/maps/api/geocode/json?address=Florence)";
request.get(url, (error, response, body) => {
let json = JSON.parse(body);
console.log(
\`City: ${json.results\[0\].formatted_address} -\`,
\`Latitude: ${json.results\[0\].geometry.location.lat} -\`,
\`Longitude: ${json.results\[0\].geometry.location.lng}\`
);
});
```
The first argument to `request` can either be a URL string, or an object of options. Here are some of the more common options you'll encounter in your applications:
- `url`: The destination URL of the HTTP request
- `method`: The HTTP method to be used (GET, POST, DELETE, etc)
- `headers`: An object of HTTP headers (key-value) to be set in the request
- `form`: An object containing key-value form data
```
const request = require('request');
const options = {
url: '[https://www.reddit.com/r/funny.json](https://www.reddit.com/r/funny.json)',
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client' }
};
request(options, function(err, res, body) {
let json = JSON.parse(body);
console.log(json);
});
```
```
```
Using the `options` object, this request uses the GET method to retrieve JSON data directly from Reddit, which is returned as a string in the `body` field. From here, you can use `JSON.parse` and use the data as a normal JavaScript object.