How does $http.jsonp() work

匿名 (未验证) 提交于 2019-12-03 02:43:01

问题:

Here is an example of a .json file:

[   {      "name":"Jon Skeets"   },    {      "name":"Bill Joy"   } ] 

If this json file is obtained as:

$http.jsonp(pathToFile).then() {      ...  } 

It returns a 404. There is nothing wrong with pathToFile I have verified it with curl, wget and the browser. But the problem is with jsonp() having to fetch .json files with the above structure. $http.get() can parse .json files with the above structure. But JSONP cant. It needs a dictionary at the top level and not an array.

To demonstrate this, I have created this firebase: https://blazing-fire-6512.firebaseapp.com/name.json

fetch the link in your browser or wget and it works. Try fetching it with Angular here and it returns 404 Request failed.

回答1:

Firebase hosting does not support JSONP. It doesn't handle the callback parameter that is used to evaluate JSONP callbacks across origins.

Say you store this JSON at URL http://example.com/name.json:

{ "name":"Jon Skeets" } 

If you access the URL http://example.com/name.json you get back exactly that JSON. And that is precisely what $http.get does.

When a server supports JSONP, it accepts a callback parameter. In such a case the URL ends up http://example.com/name.json?callback=displayName and the response is:

displayName('{ "name":"Jon Skeets" }'); 

This allows JSON data to be retrieved across origins, which is the whole reason for JSONP's existence.

Firebase's dynamic data servers support JSON. Firebase hosting does not.

Some possible solutions:

  1. If you're storing the JSON file and the application on Firebase hosting, you can just use $http.get.
  2. Since you control the JSON file, you can also simply put a function name inside name.json
  3. Store the JSON file at a host that supports JSONP. I often put them in Github Gists.
  4. Store the data structure in a Firebase hierarchical database, and not on their hosting servers


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