【问题标题】:rest api post call from mobile device web page failed来自移动设备网页的 rest api post 调用失败
【发布时间】:2022-12-11 19:07:50
【问题描述】:

下面的js代码,在桌面端可以正确执行,但是在手机chrome中出现“NetworkError”:

$.ajax({
            url: apiurl + '/sys/login',
            type: 'POST',
            async: false,
            cache: false,
            data: formData,
            processData: false,
            contentType: false,
            success: (res) => {
                if (typeof res.userName === 'string') {
                    if (res.userName.trim().length > 0) {
                        cs.writeCookie("loginstatus", `T|${res.userName}|${res.userId}|${res.employeeName}|${res.employeeId}`, 2);
                        window.location.href = "/pages/kpis/msignin.html";
                    }
                }
                else {
                    console.log('login fail')
                }
            },
            error: (res) => {
                alert(JSON.stringify(res))
            }
        })

它从移动 chrome 报告:

{"readyState":0,"status":0,"statusText":"NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://127.0.0.1/sys/login'"

谢谢!

我尝试了很多像下面等等但无法解决它:

async: false,

【问题讨论】:

    标签: javascript ajax api rest mobile


    【解决方案1】:

    127.0.0.1 是环回 IP 地址。它是运行浏览器的 IP 地址。

    您的服务器正在您的桌面上运行。

    当您的桌面浏览器请求 127.0.0.1 时,浏览器会向桌面上运行的服务器请求资源。

    当您的移动浏览器请求 127.0.0.1 时,浏览器会向移动设备上运行的服务器请求资源……但该服务器不存在。

    为移动设备上的浏览器可以访问的服务器使用 IP 地址。

    【讨论】:

      【解决方案2】:

      您看到的错误通常是由于浏览器无法与 AJAX 请求中指定的 URL 建立连接而导致的。发生这种情况的原因有多种,但一些常见原因包括:

      URL 不正确或服务器已关闭 浏览器未连接到互联网 存在网络问题或防火墙阻止连接 一种可能的解决方案是向 AJAX 请求添加错误处理,以向用户显示更有用的错误消息。您可以通过向传递给 $.ajax() 的选项对象添加一个错误属性来做到这一点,如下所示:

      $.ajax({
        // other options here
        error: function(xhr, status, error) {
          // Display an error message to the user
          alert(`Error: ${error}`);
        }
      });
      

      如果 AJAX 请求失败,这将显示带有错误消息的警报。然后,您可以使用此信息进一步解决问题。

      另一个可能的解决方案是使用 $.ajax() 方法的超时属性来指定请求的时间限制。如果请求时间超过指定时间,会自动取消并触发错误回调。如果存在网络问题或其他阻止服务器响应的问题,这有助于防止请求挂起。

      以下是如何使用超时属性的示例:

      $.ajax({
        // other options here
        timeout: 5000, // Set timeout to 5 seconds
        error: function(xhr, status, error) {
          // Display an error message if the request takes too long
          alert(`Error: Request timed out`);
        }
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-08
        • 2018-12-23
        • 1970-01-01
        • 2017-07-18
        • 2019-12-02
        • 2011-06-09
        • 2014-08-26
        • 1970-01-01
        相关资源
        最近更新 更多