如何使用http模块将嵌套对象转换为节点中的querystring



我需要帮助在POST请求中使用node.js上的标准http模块向stripe API发送嵌套对象当我使用querystring模块将json转换为querystring时,它不会给出适当的输出。它在嵌套对象中表现不佳。

这是我的有效载荷对象:

const payload = {
"card": {
"number": number,
"exp_month": exp_month,
"exp_year": exp_year,
'cvc': cvc
},
};

我的助手发送HTTP POST请求的方法:

helpers.createPaymentToken = (payload, callback) => {
//validate the parameters
if (payload) { //configure the request details
const stringPayload =queryString.stringify(payload)
//configure request details
const requestDetails = {
protocol: "https:",
hostname: "api.stripe.com",
method: "post",
path:
"/v1/tokens",
auth:config.stripe.authToken,
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": Buffer.byteLength(stringPayload),
},
};
//instantiate the request
const req = https.request(requestDetails, function (res) {
res.setEncoding('utf8');
var body = '';
console.log(res)
res.on('data', function (chunk) {
body = body + chunk;
});

res.on('end',function(){
console.log("Body :" + body);
if (res.statusCode != 200) {
callback(res.statusCode,body);
} else {
callback(null);
}
});

});
//bind to an error event so it does not get thrown
req.on("error", (e) => {
callback(e);
});
//Add the payload
req.write(stringPayload);
//end the request
req.end();
} else {
callback("Given parameters are missing on invalid");
}
};

预期的查询字符串:

card[number]=****************2&card[exp_month]=11&card[exp_year]=2021&card[cvc]=***

预期输出:(请求主体(

{
"card": {
"number": "************4242",
"exp_month": "11",
"exp_year": "2021",
"cvc": "***"
}
}

实际输出:(请求主体(

{
"card": ""
}

您的代码目前正在直接处理卡的详细信息,出于安全原因,您不应该尝试这样做。

由于您正在收集卡的详细信息,因此应使用Elements,即Stripe的UI库,在满足最低级别PCI合规性的同时,安全地收集客户端的卡详细信息。您可以在此处阅读有关PCI合规性的更多信息。

最新更新