没有在服务器上获得完整的json响应(nodejs)

时间:2018-01-18 05:48:01

标签: javascript arrays json node.js object

我有一个第三方短信api:

我正在通过该api发送消息,如果把响应的console.log看起来像我的服务器中这样:

connection:
  Socket {
    connecting: false,
    _hadError: false,
    _handle: [Object],
    _parent: null,
    _readableState: [Object],
    readable: true,
    domain: null,
    _events: [Object],
    _eventsCount: 9,
    _maxListeners: undefined,
    _writableState: [Object],
    writable: true,
    allowHalfOpen: false,
    _bytesDispatched: 182,
    _sockname: null,
    _pendingData: null,
    _pendingEncoding: '',
    server: null,
    _server: null,
    parser: [Object],
    _httpMessage: [Circular],
    read: [Function],
    _consuming: true,
    [Symbol(asyncId)]: 1805,
    [Symbol(bytesRead)]: 0 },
 _onPendingData: [Function: noopPendingOutput],
 agent:
  Agent {
    domain: null,
    _events: [Object],
    _eventsCount: 1,
    _maxListeners: undefined,
    defaultPort: 80,
    protocol: 'http:',
    options: [Object],
    requests: {},
    sockets: [Object],
    freeSockets: {},
    keepAliveMsecs: 1000,
    keepAlive: false,
    maxSockets: Infinity,
    maxFreeSockets: 256 },
 socketPath: undefined,
 timeout: undefined,
 method: 'GET',
 _ended: false,
 res: [Circular],
 aborted: undefined,
 timeoutCb: null,
 upgradeOrConnect: false,
 parser:
  HTTPParser {
    '0': [Function: parserOnHeaders],
    '1': [Function: parserOnHeadersComplete],
    '2': [Function: parserOnBody],
    '3': [Function: parserOnMessageComplete],
    '4': null,
    _headers: [],
    _url: '',
    _consumed: false,
    socket: [Object],
    incoming: [Circular],
    outgoing: [Circular],
    maxHeaderPairs: 2000,

我的api代码(nodejs):

var options = {
   host: 'xxxxxx',
   port: 80,
   path: xxxxxxx,
   method: 'GET'
};
var req = http.request(options, function (res) {
   console.log('FULL RESPONSE: ', res);
   res.setEncoding('utf8');
   res.on('data', function (chunk) {
      console.log('BODY: ' + chunk);
   });
});

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

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

我希望在我的服务器(终端)中看到没有这种[Object] [Array]和[Circular]的完整响应。

如果我把JSON.stringify它抛出错误。

1 个答案:

答案 0 :(得分:0)

在这里阐述我的评论:

res对象是一个流对象。您想要的数据可能不会在这里。您必须使用res.on('data',function(chunk){...})部分中的字符串/缓冲区构建数据。数据可能以多个块的形式出现,因此您可能还需要使用res.on('end',function(){...})来确定何时收到所有数据。之后,您可以处理字符串/缓冲区并使用JSON.parse来获取所需的数据

示例演示:

var req = http.request(options, function (res) {
   res.setEncoding('utf8');
   // Create a new Buffer
   var buffer = Buffer.from('');
   res.on('data', function (chunk) {
      // Each time a chunk comes through, write it to the buffer
      console.log('BODY: ' + chunk);
      buffer.write(chunk);
   });
   res.on('end',function(){
      // The request is complete here, try to get the JSON string and parse it
      // TODO: handle possible parse exception
      var data = JSON.parse(buffer.toString('utf8'));
   });
});

我建议使用像node-fetchrequest这样的库,它允许您使用回调/承诺并抽象出流。这些在大多数情况下都能很好地工作,除非你做的是开箱即​​用的东西

相关问题