1

I just started working with Nodejs.

I am using Restify to get data from: http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo'.

My code below gives me an error: {"code":"ResourceNotFound","message":"/ does not exist"}

var restify =require("restify");

var server = restify.createServer();

server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());

server.get('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo', function (req, res) {
    console.log(req.body);
    res.send(200,req.body);
});

server.listen(7000, function () {
    console.log('listening at 7000');
});
javascript novice
  • 777
  • 2
  • 9
  • 28

2 Answers2

1

That's because Restify is for creating REST endpoints, not consuming them. You should check out this SO post for help consuming data from an API.

e.g. create test.js with the following:

var http = require('http');
var options = {
  host: 'api.geonames.org',
  path: '/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo'
};

var req = http.get(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));

  // Buffer the body entirely for processing as a whole.
  var bodyChunks = [];
  res.on('data', function(chunk) {
    // You can process streamed parts here...
    bodyChunks.push(chunk);
  }).on('end', function() {
    var body = Buffer.concat(bodyChunks);
    console.log('BODY: ' + body);
    // ...and/or process the entire body here.
  })
});

req.on('error', function(e) {
  console.log('ERROR: ' + e.message);
});

then run node test.js.

Community
  • 1
  • 1
pherris
  • 17,195
  • 8
  • 42
  • 58
  • 1
    If javascript novice wants to both consume an API and provide an API then it would be good to check out the built in clients in restify. http://restify.com/#client-api – HeadCode Nov 04 '15 at 18:58
0

I found what I was looking for. You can use restify client to get JSON data:

Here is my solution:

var restify = require("restify");

 function getJSONDataFromUrl(){
    var query = "?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo";
    var options = {};
    options.url = "http://api.geonames.org";
    options.type = options.type || "json";
    options.path = "/citiesJSON" + query;
    options.headers = {Accept: "application/json"};


    var client = restify.createClient(options);

    client.get(options, function(err, req, res, data) {
        if (err) {
            console.log(err);
            return;
        }
        client.close();
        console.log(JSON.stringify(data));

        return JSON.stringify(data);
    });
}

getJSONDataFromUrl();
javascript novice
  • 777
  • 2
  • 9
  • 28