簡體   English   中英

節點 JS Https.Request() 方法 req,res on,data,end 事件不起作用

[英]Node JS Https.Request() method req,res on,data,end events are not working

我正在嘗試從節點 JS https 模塊調用 STRIPE api,在控制到達下一行后,req.end() 被執行並退出 ZC1C425268E68385D14AB5074C17Z9,結果看不到任何錯誤。我哪里錯了

請找到完整的代碼片段,我需要在 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')
   });

當我嘗試通過 postman 嘗試 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'
}

試試這個它可能對你有用。

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM