首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将ClientIP添加到xhr post请求

将ClientIP添加到xhr post请求
EN

Stack Overflow用户
提问于 2020-10-12 22:21:45
回答 1查看 226关注 0票数 0

我的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?

代码语言:javascript
复制
      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;
      };
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-12 22:25:28

$.get是一个异步函数,因此它不返回IP地址。相反,您需要将xhr调用包装在$.get函数中。

代码语言:javascript
复制
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地址可以由服务器而不是前端添加。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64326059

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档