我正在执行 http.request,如果服务器响应错误 500,我想访问请求期间发送的数据,以便重试该请求。如何从响应回调范围访问 requestBodyData 参数?
见下文:
var arrayofobjects = [
{
"name" : "peter",
"age" : "24"
},
{
"name" : "gleice",
"age" : "19"
},
{
"name" : "pedro",
"age" : "34"
}
];
for(var x=0; x<arrayofobjects.length; x++){
sendModelInputData(arrayofobjects[x]);
}
function sendModelInputData (requestBodyData) {
const req = https.request(connectionInfo, (res) => {
logger.info(`STATUS: ${res.statusCode}`)
logger.debug(`HEADERS: ${JSON.stringify(res.headers)}`)
//how to access requestBodyData from here????
res.setEncoding('utf8');
res.on('data', (chunk) => {
logger.info(`BODY: ${chunk}`);
});
res.on('end', () => {
//console.log('No more data in response.');
});
});
req.on('error', (e) => {
//console.error(`problem with request: ${e.message}`);
logger.error(`problem with request: ${e.message}`);
});
//req.end(postData);
req.end(JSON.stringify(requestBodyData));
}
最佳答案
从您的评论中,我意识到您正在 sendModelInputData
之外更改 requestBodyData
,因此您必须克隆它以保留原始值。您可以使用Object.assign
来实现这一点。
function sendModelInputData (requestBodyData) {
requestBodyData = Object.assign({}, requestBodyData); // Shallow clone
// On retry use requestBodyData which will be the same data you sent
}
检查以下问题,以了解发生了什么。
关于javascript - Node.js https.request : Access the requested data from the callback response scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50008246/