When I type somedomain.com/some_api_url?_var1=1
into a browser, the response is {"1":"descriptive string"}
, where 1
is a numerical index variable whose value could range from 1
to n
. And where "descriptive string" is some text that summarizes what the index represents.
How can I integrate the JSON response
from the somedomain.com/some_api_url?_var1=1
api url into the very simple Node.js
and Express.js
example below?
For testing purposes, the very simple app.js
shown below returns "Hello World" when the user requests http : // localhost : 3000
from their web browser. What specific changes need to be made to the code below so that the web browser responds to the request with:
Index is: 1
Description is: descriptive string
instead of responding with "Hello World"?
Here is the current code for app.js
:
var express = require('express');
var http = require('http');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Here is my current attempt, which results in the console printing Got a response: undefined
, and with the browser remaining hung up because nothing is returned to the browser as a response
:
var express = require('express');
var http = require('http');
var app = express();
app.get('/', function (req, res) {
var url = 'somedomain.com/some_api_url?_var1=1';
http.get(url, function(res){
var body = '';
res.on('data', function(chunk){
body += chunk;
});
res.on('end', function(){
var fbResponse = JSON.parse(body);
console.log("Got a response: ", fbResponse.picture);
});
}).on('error', function(e){
console.log("Got an error: ", e);
});
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
The get
example code was adapted from the example at this link.