我的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;
};发布于 2020-10-12 22:25:28
$.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地址可以由服务器而不是前端添加。
https://stackoverflow.com/questions/64326059
复制相似问题