微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

将ClientIP添加到xhr发布请求

如何解决将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,因此您可能还可以在xhr调用中使用$.post。另外,根据提交$.post的位置,IP地址可以由服务器而不是在前端添加。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。