简体   繁体   English

如何修复Node.js http发布请求或处理错误以更有效地进行调试?

[英]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. 我认为这是基于data字段的原因,但我不确定。 This api returns JSON, so I don't see the response as being the problem. 此api返回JSON,因此我认为响应不是问题。 What I am most concerned with is better error handling in Node. 我最关心的是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)
          })
      })
    }
body += data

make sure data is string or buffer. 确保数据是字符串或缓冲区。 You can cast to it if necessary. 如有必要,可以强制转换为它。

For debugging, if you use alot of Promises, you can use the decorator pattern to log usefull things 对于调试,如果您使用大量Promises,则可以使用装饰器模式记录有用的内容

Since options.data is a string try setting the Content-Type in the headers to text/html . 由于options.data是字符串,请尝试将标题中的Content-Type设置为text/html

If you want the content-type to be application/json, try setting options.data to a json object. 如果您希望内容类型为application / json,请尝试将options.data设置为json对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM