通过 Angular 从 Firebase 托管获取 JSONP 文件 [英] Obtaining JSONP files from Firebase hosting through Angular
问题描述
我正在尝试从远程 Firebase 服务器获取 .json
文件.
function fetchData(remoteJsonId){var url = "https://myAppName.firebaseapp.com/topics/"+remoteJsonID;控制台日志(网址);//此变量扩展为有效的完整域名,并在 wget 和浏览器上都返回成功$http.jsonp(url).then(功能(响应){},功能(错误){console.log(err.status)//这会在控制台上发布404".});}
但是如果我在浏览器中打开 url
json 文件加载.即使我 wget url
加载 json 文件.但是通过 angular 它返回一个 404
not found.
现在 .json
远程文件具有以下结构:
上述文件可以使用 $http.get() 获取,但不能使用 $http.jsonp() 获取.JSONP 无法解析具有上述结构的 .json 文件.我该如何解决这个问题?
您需要在传递给 $http.jsonp
?callback=JSON_CALLBACK>.
jsonp(url, [config]);执行 JSONP 请求的快捷方法.参数参数类型详细信息网址字符串指定请求目标的相对或绝对 URL.回调的名称应该是字符串 JSON_CALLBACK.
最后一行是您所缺少的.
一个简单的例子(使用 Firebase 数据库,而不是 Firebase 托管):
var app = angular.module('myapp', []);app.controller('mycontroller', function($scope, $http) {var url = 'https://yourfirebase.firebaseio.com/25564200.json';$http.jsonp(url+'?callback=JSON_CALLBACK').then(功能(响应){控制台日志(响应数据);//你的对象在 resp.data 中},功能(错误){控制台错误(错误状态)});});
如果你想看到它工作:http://jsbin.com/robono/1/watch?js,控制台
I am trying to obtain a .json
file from remote firebase server.
function fetchData(remoteJsonId){
var url = "https://myAppName.firebaseapp.com/topics/"+remoteJsonID;
console.log(url); //This variable expands to the full domain name which is valid and returns success both on wget and the browser
$http.jsonp(url).then(
function(resp){
},
function(err){
console.log(err.status) // This posts "404" on console.
}
);
}
But If I open url
in the browser the json file loads. Even if I wget url
the json file loads. But through angular it returns a 404
not found.
Now the .json
remote file has this structure:
[
{
"hello":"Europe"
},
{
"hello":"USA"
}
]
The above file can be fetched using $http.get() but not with $http.jsonp(). JSONP cant parse .json file with the above structure. How can I work around this?
You need to specify a ?callback=JSON_CALLBACK
in the URL that you pass to $http.jsonp
.
From Angular's $http.jsonp
documentation:
jsonp(url, [config]);
Shortcut method to perform JSONP request.
Parameters
Param Type Details
url string
Relative or absolute URL specifying the destination of the request.
The name of the callback should be the string JSON_CALLBACK.
That last line is what you're missing.
A simple example (using a Firebase database, not Firebase hosting):
var app = angular.module('myapp', []);
app.controller('mycontroller', function($scope, $http) {
var url = 'https://yourfirebase.firebaseio.com/25564200.json';
$http.jsonp(url+'?callback=JSON_CALLBACK').then(
function(resp){
console.log(resp.data); // your object is in resp.data
},
function(err){
console.error(err.status)
}
);
});
In case you want to see it working: http://jsbin.com/robono/1/watch?js,console
这篇关于通过 Angular 从 Firebase 托管获取 JSONP 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!