繁体   English   中英

将 ClientIP 添加到 xhr post 请求

[英]Add ClientIP to xhr post request

我的 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 地址可以由服务器而不是前端添加。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM