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

Node Restify use case to get data gives a "ResourceNotFound"

本文关键字:一个 ResourceNotFound 数据 获取 Restify Node      更新时间:2023-09-26

我刚开始使用Nodejs。

我正在使用Restify从以下位置获取数据:http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&东部=-22.4&west=55.2&lang=de&username=demo。

下面的代码给了我一个错误:{"code":"ResourceNotFound","message":"/不存在"}

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用于创建REST端点,而不是使用它们。您应该查看这篇SO文章,以获取使用API数据的帮助。

例如,使用以下内容创建test.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);
});

然后运行CCD_ 2。

我找到了我要找的东西。您可以使用restify客户端获取JSON数据:

这是我的解决方案:

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