Node Restify用例获取数据给出一个“ResourceNotFound”

我刚开始使用Nodejs。

我使用Restify从http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo获取数据。

我的代码给了我一个错误:{“code”:“ResourceNotFound”,“消息”:“/不存在”}

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'); }); 

这是因为Restify用于创build REST端点,而不是消耗它们。 你应该看看这个SOpost,以帮助消费API的数据。

例如使用以下命令创buildtest.js

 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); }); 

然后运行node test.js

我find了我正在寻找的东西。 您可以使用restify客户端来获取JSON数据:

这是我的解决scheme:

 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();