问题描述
我的ErrorHandler可以捕获错误,但是我无法添加客户端ip。我不习惯使用Ajax,xhr等,而且我仍然在学习javascript。
我在后端得到以下输出:
ERROR {"timestamp":"2020-10-12T22:14:57.113Z","ip":{"readyState":1},"message":"Error in mounted hook: \"ReferenceError: asd is not defined}
为什么我得到"ip":{"readyState":1}
以及我如何得到我的真实IP?
window.onerror = function(timestamp,ip,message,source,lineno,colno,error) {
const toSend ={
"timestamp": new Date(),"ip": $.get('https://ipinfo.io/ip',function(dataIP){
return {
dataIP
}
}),"message": message,"source": source,"lineo": lineno,"colno": colno,"error":error,};
const jsonString = JSON.stringify(toSend);
const xhr = new XMLHttpRequest();
xhr.open("POST","http://localhost:8090/api/auth/event");
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(jsonString);
return false;
};
解决方法
$.get
是一个异步函数,因此它不返回IP地址。相反,您需要将xhr调用包装在$.get
函数中。
window.onerror = function(timestamp,ip,message,source,lineno,colno,error) {
$.get('https://ipinfo.io/ip',function(dataIP){
const toSend = {
"timestamp": new Date(),"ip": dataIP,"message": message,"source": source,"lineo": lineno,"colno": colno,"error":error,};
const jsonString = JSON.stringify(toSend);
const xhr = new XMLHttpRequest();
xhr.open("POST","http://localhost:8090/api/auth/event");
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(jsonString);
});
return false;
};
$.get
可能是jQuery.get,它返回一个jqXHR对象,这就是为什么它说readyState
。
要注意的另一件事是,由于$.get
是jQuery,因此您可能还可以在xhr
调用中使用$.post
。另外,根据提交$.post
的位置,IP地址可以由服务器而不是在前端添加。