将 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 是一个异步函数,因此它不会 return 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,其中 return 是一个 jqXHR 对象,这就是它说 readyState.

的原因

另一件需要注意的事情是,由于 $.get 是 jQuery,您可能还可以将 $.post 用于 xhr 调用。此外,根据提交 $.post 的位置,IP 地址可以由服务器而不是在前端添加。