【问题标题】:Node JS Https.Request() method req,res on,data,end events are not workingNode JS Https.Request() 方法 req,res on,data,end 事件不起作用
【发布时间】:2021-06-05 18:05:40
【问题描述】:

我正在尝试从 Node JS https 模块调用 STRIPE api,在控件到达下一行后,req.end() 被执行并退出该函数,我看不到任何错误、结果或任何东西。 . 不知道我哪里错了

请找到完整的sn-p,我需要在https.request调用成功或错误响应后做一些操作

const https = require('https');
var fs = require('fs');
var qs = require('querystring');

var postData = qs.stringify({
       'amount': '2000',
       'currency': 'usd',
       'source': 'tok_visa',
       'description': 'pizza order'
   });
 
 var options = {
   'method': 'POST',
   'host': 'api.stripe.com',
   'path': '/v1/charges',
   'headers': {
     'Authorization': 'Bearer sk_test_4eC39HqLyjWDarjtT1zdp7dc',
       'Content-Type': 'application/x-www-form-urlencoded',
       'content-length': Buffer.byteLength(postData)
   },
   'maxRedirects': 20
 };
var req = https.request(options, function (res) {
   var chunks = [];
 
   res.on("data", function (chunk) {
     chunks.push(chunk);
   });
 
   res.on("end", function (chunk) {
       var body = Buffer.concat(chunks);
       callback(body);
   });
 
     res.on("error", function (error) {
         callback(error);
     console.error(error);
   });
 });
 
 
 
 req.write(postData);
 
   req.end(() => {
       console.log('req end')
   });

当我尝试通过邮递员 api 时,它可以工作,但如果我使用 cmd PING,它说找不到主机。虽然我正在尝试使用 NODE JS 进行相同的操作,但出现以下错误

Error: socket hang up
    at connResetException (internal/errors.js:607:14)
    at TLSSocket.socketOnEnd (_http_client.js:499:23)
    at TLSSocket.emit (events.js:388:22)
    at endReadableNT (internal/streams/readable.js:1336:12)
    at processTicksAndRejections (internal/process/task_queues.js:82:21) {
  code: 'ECONNRESET'
}

【问题讨论】:

  • 请求可能有错误。您是否尝试为请求 error 事件添加事件处理程序?
  • 我也试过了,但它没有帮助,即使我打印的事件导致控制台。但它不工作

标签: javascript node.js https


【解决方案1】:

试试这个,它可能对你有用。

var options = {
       'method': 'POST',
       'host': 'api.stripe.com',
       'path': '/v1/charges',
       'headers': {
        'Authorization': 'Bearer sk_test_4eC39HqLyjWDarjtT1zdp7dc',
           'Content-Type': 'application/x-www-form-urlencoded',
           'content-length': Buffer.byteLength(postData)
       }
      };
        
        http.request(options, function(res) {
          res.setEncoding('utf8');
          res.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
          });
        }).end();

【讨论】:

  • 感谢您的输入,但这不起作用。我用 Promise 包装了完整的请求,并在问题中添加了打印的异常。它将更具体地解决我的问题
猜你喜欢
  • 2015-12-24
  • 2018-01-31
  • 2020-11-11
  • 2015-10-22
  • 2012-12-29
  • 1970-01-01
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多