[英]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我正在尝试从节点 JS https 模块调用 STRIPE api,在控制到达下一行后,req.end() 被执行并退出 ZC1C425268E68385D14AB5074C17Z9,结果看不到任何错误。我哪里错了
Please find the complete snippet, I need to do some operation after the success or error response from the https.request call请找到完整的代码片段,我需要在 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')
});
When i tried to api via postman, its working but if i PING using cmd, it say couldnt not find host.当我尝试通过 postman 尝试 api 时,它可以工作,但是如果我使用 cmd PING,它说找不到主机。 While i am trying the same with NODE JS getting the below error
虽然我正在尝试使用 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'
}
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.