[英]AngularJS & Cordova $http issues - browser works fine, app does not
I am writing a Phonegap/Cordova application using AngularJS consuming a Rails API.我正在使用使用 Rails API 的 AngularJS 编写 Phonegap/Cordova 应用程序。 I'm attempting to use
$http
to hit the API during a login event.我试图在登录事件期间使用
$http
来访问 API。 When emulating my application on Chrome (launching using cordova run
) $http works great as expected.在 Chrome 上模拟我的应用程序时(使用
cordova run
启动)$http 可以正常工作。
However, anytime I use $http
on the actual PhoneGap developer app, it will error out and never hit the API.但是,每当我在实际的 PhoneGap 开发者应用程序上使用
$http
时,它都会出错并且永远不会命中 API。 Rails API is using the gem rack-cors
to allow CORS - it works with several other AngularJS applications and is relatively unsafe only for debug purposes. Rails API 使用 gem
rack-cors
来允许 CORS - 它可以与其他几个 AngularJS 应用程序一起使用,并且仅用于调试目的相对不安全。
# config/application.rb
CORS_ALLOW_ORIGIN = "*"
CORS_ALLOW_METHODS = %w{GET POST PUT OPTIONS DELETE}.join(',')
CORS_ALLOW_HEADERS = %w{Content-Type Accept X-Auth-Token AllowedHeader}.join(',')
... other config stuff ...
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => :any
end
end
config.action_dispatch.default_headers = {
"Access-Control-Allow-Origin" => CORS_ALLOW_ORIGIN,
"Access-Control-Allow-Methods" => CORS_ALLOW_METHODS,
"Access-Control-Allow-Headers" => CORS_ALLOW_HEADERS
}
What I've tried: 1) update phonegap config.xml
to unsafely allow anything access我尝试过的:1)更新 phonegap
config.xml
以不安全地允许任何访问
<access origin='*'
allows-arbitrary-loads-in-media='true'
allows-arbitrary-loads-in-web-content='true'
allows-local-networking='true' />
<allow-intent href="*" />
<allow-navigation href="*" />
2) use angular .run
to add headers for every request made 2) 使用 angular
.run
为每个请求添加标头
angular.module("services")
.run(function($http) {
$http.defaults.headers.common['AllowedHeader'] = "origin";
})
3) manually build up each request with other headers 3) 用其他标头手动构建每个请求
login: function(credentials) {
var request = {
url: baseURI + "/user_sessions/",
method: "POST",
params: {
user_session: credentials,
},
headers: {
"Cache-Control": "no-cache",
"Content-Type": "application/json"
}
}
return $http(request);
}
4) use cordova-whitelist-plugin
4) 使用
cordova-whitelist-plugin
Any thoughts out there?有什么想法吗? I've seen many questions referencing how
$http
is working in browser but failing on the phone.我看到很多问题都提到
$http
在浏览器中是如何工作的,但在电话上却失败了。
Turns out the problem was not with $http, but rather the path $http was given during the POST.原来问题不在于 $http,而是 $http 在 POST 期间给出的路径。 Our baseURI variable was set to
//api.site.com
which worked fine with a browser but not with the mobile app.我们的 baseURI 变量被设置为
//api.site.com
,它在浏览器上工作正常,但在移动应用程序上却没有。 Changing it to be more explicit https://api.site.com
worked great.将其更改为更明确的
https://api.site.com
效果很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.