PhoneGap doesn't want to use REST service no matter what I do

旧巷老猫 提交于 2019-12-12 01:04:51

问题


I have a PhoneGap app that I am using AngularJS with. I'm using a pretty simple $http call to my Node backend:

$http.get("http://localhost:6969/random")
   .then(function(response) {
        $scope.images = response.data;
  });

No matter what, PhoneGap never hits the backend. I have tested it in a normal browser and it works as expected.

I have obviously read a bunch about it and most people fix it using whitelisting, but in my config.xml, my whitelisting is about as open as can be:

<plugin name="cordova-plugin-whitelist" source="npm" spec="1.1.0" />
  <allow-navigation href="*" subdomains="true" />
  <allow-intent href="*" subdomains="true"/>
  <access origin="*" subdomains="true"/> <!-- Required for iOS9 -->

What do I have to change? Been wrestling this bug for a few days off and on and it's a bit annoying to not be able to actually create new cool features in my free time.

EDIT: I am serving the app using phonegap serve and testing it using the PhoneGap Developer App.


回答1:


I would suggest your Content Security Policy might need to be modified to include a connect-src clause to specify where Ajax requests can go to.

Taking the CSP meta tag that you posted in the comments:

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src: 'self' 'unsafe-inline' 'unsafe-eval'" />

I would suggest amending this to open up Ajax requests to anywhere, see if that helps then reign it in to just domain(s) you want to support after.

Suggested CSP would be:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; connect-src *">

If that works and you want to lock down to just one domain later you'd want something like:

<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; connect-src http://api.mydomain.com">

Additionally I think you will need to change your app's code to connect to your server by hostname or IP address, so so that on the device it doesn't confuse 'localhost' with the device itself and try to make a connection to port 6969 on the device.

So:

$http.get("http://localhost:6969/random")

May need to become:

$http.get("http://myhost.mydomain.com:6969/random")

Or

$http.get("http://xxx.xxx.xxx.xxx:6969/random")

There's some resources on this online:

  • Content Security Policy page
  • A blog post I wrote on this topic


来源:https://stackoverflow.com/questions/36731512/phonegap-doesnt-want-to-use-rest-service-no-matter-what-i-do

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!