代码之家  ›  专栏  ›  技术社区  ›  xRobot

为什么我不能用Nodejs检索json数据?

  •  0
  • xRobot  · 技术社区  · 6 年前

    我只需要一种方法从特定的url检索json数据。 我写了这个程序:

    'use strict';
    var http = require('http');
    var request = require("request");
    
    var url = "https://restcountries.eu/rest/v2/name/united"
    
    
    var server = http.createServer(function (req, res) {
      res.writeHead(200, {'Content-Type': 'text/plain'});
    
      request({
          url: url,
          json: true
      }, function (error, response, body) {
          if (!error && response.statusCode === 200) {
             res.write(JSON.parse(body)) // Print the json response
          }else{
             res.write("error");
             res.end();
          }
      })
    
    
    })
    
    server.listen(1338, '127.0.0.1');
    
    console.log('Server running at http://127.0.0.1:1338/');
    

    但我有个错误:

    # node mytest.js
    Server running at http://127.0.0.1:1338/
    undefined:1
    [object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
     ^
    
    SyntaxError: Unexpected token o in JSON at position 1
        at JSON.parse (<anonymous>)
        at Request._callback (/home/xxx/Nodejs/Esempi/emilianotest2.js:18:25)
        at Request.self.callback (/home/xxx/Nodejs/Esempi/node_modules/request/request.js:185:22)
        at Request.emit (events.js:160:13)
        at Request.<anonymous> (/home/xxx/Nodejs/Esempi/node_modules/request/request.js:1161:10)
        at Request.emit (events.js:160:13)
        at IncomingMessage.<anonymous> (/home/xxx/Nodejs/Esempi/node_modules/request/request.js:1083:12)
        at Object.onceWrapper (events.js:255:19)
        at IncomingMessage.emit (events.js:165:20)
        at endReadableNT (_stream_readable.js:1101:12)
    

    编辑:

    这是我删除时得到的错误JSON.parse文件:

    Server running at http://127.0.0.1:1338/
    _http_outgoing.js:651
        throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'first argument',
        ^
    
    TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be one of type string or Buffer
        at write_ (_http_outgoing.js:651:11)
        at ServerResponse.write (_http_outgoing.js:626:10)
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   Amadan    6 年前

    因为你给出了参数 json: true , request JSON.parse ,它在被解析之前被转换成一个字符串;数组中的对象得到熟悉的 [object Object] 陈述,以及 JSON.parse文件 [对象] 看起来不像是一个合适的数组。

    try {
      let json = JSON.stringify([{a:1}])
      console.log("parsed once:");
      console.log(JSON.parse(json));
      console.log("parsed twice:");
      console.log(JSON.parse(JSON.parse(json)));
    } catch(e) {
      console.error(e.message);
    }

    编辑:删除时 ,你最终试图 res.write 一个物体。 资源写入 不喜欢这样(Roland Starke在评论中已经注意到);它更喜欢字符串:

    res.write(JSON.stringify(body))