简体   繁体   中英

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

I am trying to call a STRIPE api from the Node JS https module, after the control reaching the below line, req.end() is executed and exited the function, I couldn't see any error, result or anything.. Not sure where am i going wrong

Please find the complete snippet, I need to do some operation after the success or error response from the https.request call

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')
   });

When i tried to api via postman, its working but if i PING using cmd, it say couldnt not find host. While i am trying the same with NODE JS getting the below error

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'
}

Try this it might work for you.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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