【问题标题】:Cordova (Phonegap) https work and debugCordova (Phonegap) https 工作和调试
【发布时间】:2016-05-07 07:46:17
【问题描述】:

有带有 api 的 https 站点。

需要科尔多瓦 (angularjs) 的 https api 工作。

我还想在 webbrowser (chrome) 中调试 angularjs 应用程序,因为它非常快(与重建和部署相比)。

简单代码

$http({
    method: 'POST',
    crossDomain: true,
    xhrFields: { withCredentials: false },
    url: 'https://.../api/Auth',
    data: { email: user, password: password }
    }).
    then(function (response) {
        console.log("0", response);
    }, function (response) {
        console.log("1", response);
    });

$.ajax({
    type: "POST",
    url: 'https://.../api/Auth',
    xhrFields: {
        withCredentials: true
    },
    crossDomain: true,
    data: { email: user, password: password },
    success: function (response) { console.log("2", response) },
});
  1. cordova 调试结果(Visual Studio,Windows-x64)

第一个请求

HTTP500: SERVER ERROR - 服务器遇到意外情况,无法完成请求。 (XHR): GET - https://.../api/Auth?AspxAutoDetectCookieSupport=1

两次,因为 $http + $.ajax

第二个和下一个请求 - 返回正确响应(也是两次)

  1. chrome 中的结果

所有请求

a) $http 使用 OPTION 方法而不是 POST

b) $http 错误 XMLHttpRequest 无法加载https://.../api/Auth。预检响应无效(重定向)

c) $.ajax 使用正确的POST

d) $.ajax 错误 XMLHttpRequest 无法加载https://.../api/Auth。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问 Origin 'http://local1.test'。

问题

  1. 如何在cordova和chrome中使用相同代码的https?

  2. cordova 跳过第一个请求并作为第二个请求的正确性如何?

【问题讨论】:

  • 你使用的是cordova和angular,为什么不使用ionic呢?另外,Angular 中的 $http 服务是一个 ajax 请求,因此请使用它而不是 $.ajax,因为您使用的是 Angular。也很高兴向工厂提出请求以保持关注点分离
  • 感谢 ionic。我有角度的经验。我需要简单的应用程序。 $.ajax 是错误示例。 https (CORPS) 中的问题。

标签: javascript angularjs ajax cordova google-chrome


【解决方案1】:

从 Cordova 5 开始,您需要使用 Cordova Whitelist Plugin。

安装该插件后,您需要修改项目的config.xml 文件。对于您的网络请求,您需要添加类似于以下内容的<access> 标签:

<access origin="http://*.google.com" />

您还需要为您的应用配置Content Security Policy。我建议参考Cordova Whitelist Plugin documentation 以获得指导。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-23
    • 2015-02-01
    • 1970-01-01
    • 2012-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    相关资源
    最近更新 更多