javascript - 将 ClientIP 添加到 xhr 发布请求
问题描述
我的 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,您可能也可以使用它$.post
来xhr
调用。此外,根据$.post
提交的位置,IP 地址可以由服务器而不是前端添加。
推荐阅读
- python - kivy中的功能登录屏幕
- python - 如何在 html iframe 的源代码中包含 python 函数?
- css - React bootstrap open-iconic 显示“T”符号而不是相关图标
- excel - 使用 VBA 对突出显示的单元格进行排序
- python - 在列表列表中查找最大值
- java - mapStruct 中何时使用表达式?
- powershell - 通过 CSV 文件将联系人导入 AD
- python-3.x - 使用 monotonically_increasing_id 不会连续给出 ID (pyspark)
- kubernetes - Is it possible to undo kubernetes cluster delete command?
- vue.js - 对将哪些 Vuejs 文件推送到 NPM 以获取库感到困惑