Monday, 24 April 2017

How can I fix a Node.js http post request or handle errors to more efficiently debug?

This example lacks some context, I know. But this request returns this error:

TypeError: Invalid data, chunk must be a string or buffer, not object

I think it is because of the of what is being based to the data field but I can't be sure. This api returns JSON, so I don't see the response as being the problem. What I am most concerned with is better error handling in Node. I could fix this a lot quicker if I knew exactly what the culprit was for the error. Any help would be appreciated!

Program.prototype.produceSomething = function(){
      const headers = {
        'Authorization': 'API_KEY',
        'Content-Type': 'application/json',
      }
      const options = {
          url: 'SOME_API',
          path: 'SOME_PATH',
          method: 'POST',
          data: 'dataString',
          headers: headers,
      };
      let body = "";
      return new Promise(function(resolve, reject){
        let request = https.request(options,
          function(response){
            response.on('data', function(data){
              body += data;
            })
            response.on('end', function(){
              body = JSON.stringify(body)
              resolve(body);
            })
          })
          request.on('error', function(err){
            reject(err)
          })
      })
    }



via colbisaurusrex

No comments:

Post a Comment