我编写了示例 Node 应用程序来处理错误数据,例如数据库连接错误、端口冲突错误、进程未捕获的异常。当发生错误时,会发出 http 请求来处理错误。在这种情况下,当 Node 进程异常存在时,我可以处理 process.on('exit')
函数中的存在,但无法发送http请求,进程正在快速退出。
任何人都可以建议如何在进程退出之前发送 http 请求并在 Node.js 上获取响应。下面是在进程存在时发送http请求的示例代码
var http = require('http');
var errorData=null;
var sendErrorReport = function(data,callback){
var options = {
host : connection.host,
path : "/api/errorReport",
port : connection.port,
method : 'POST',
timeout: connection.timeInterval,
headers:{
'Content-Type':'application/json',
'Content-Length': Buffer.byteLength(data)}
}
var request = http.request(options,function(response){
callback(response);
});
request.on('error',function(err){
console.log("On Error");
callback(err);
});
request.on('timeout', function(err){console.log("On Timeout");
callback(err);});
request.write(data);
request.end();
}
process.on('uncaughtException', function ( err ) {
errorData = err;
});
process.on('exit',function(code){
sendErrorReport(errorData,function(err,res){
console.log(res);
});
})
最佳答案
遇到同样的问题, 根据文档https://nodejs.org/api/process.html#process_event_exit
“事件:‘退出’监听器函数必须仅执行同步操作。”使向其他系统发送请求变得困难。
一种可能的解决方法是执行另一个脚本/cmd,例如。
import exec from 'child_process'
mocha.run(failures => {
process.on('exit', () => {
exec.execSync(some cmd, function (error, stderr) {
if (error) {
throw (error);
}
}
}
关于node.js - 在 Node 进程退出时发送http请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45507882/