官术网_书友最值得收藏!

The JSON feed generation

Serving a JSON (JavaScript Object Notation) feed is a useful alternative to XML, as it requires the transfer of less data and is often easier and faster to deal with rather than dealing with XPath. The getJSONfeed method is part of the Blog class, shown as follows:

String getJSONFeed() {
  List posts = new List();
  IDs.forEach((int postID) {
    BlogPost post = getBlogPost(postID);
    Map jsonPost = {};
    jsonPost["id"] = post._id;
    jsonPost["date"] = post._date;
    jsonPost["title"] = post._title;
    jsonPost["url"] = "http://127.0.0.1:8080/post${post._id}.html";
    posts.add(jsonPost);
    });
  return JSON.encode(posts);
}

This method follows the same approach as RSS, with the main data structure being a list this time and the items being entries in that list. The list can be converted to JSON using the JSON.encode method from dart:convert:

[
…
 {"id" : 6,
   "date" : "02/05/2015",
    "title" : "Lemur Facts",
    "url" : "http://127.0.0.1:8080/post6.html"},
…
]

Note

The JSON feed is served to http://127.0.0.1:8080/feed.json and can be viewed directly in most web browsers.

Serving the JSON

The serving of JSON requires not only the correct type to be specified, but also the security needs to be dealt with for the consumption of this data feed from another web domain:

    void _serveJsonFile(HttpRequest request) {
    request.response
      ..statusCode = HttpStatus.OK
      ..headers.set('Content-Type', 'application/json')
      ..headers.add("Access-Control-Allow-Origin", "*")
      ..headers.add(
          "Access-Control-Allow-Methods", "POST,GET,DELETE,PUT,OPTIONS")
      ..write(hostedBlog.getJSONFeed())
      ..close();
  }

The content type is set to application/json, which triggers the XML display in the browser. The access control (CORS) is set to allow any origin and a set of HTTP verbs.

Note

Cross-origin resource sharing (CORS) is a technology that permits restricted resources, such as scripts to be requested from other web domains. For example, a news site wants to request the headlines in the JSON format from a blog to display them.

By default, resources can only be loaded from the same domain. CORS allows specific resources, and actions (HTTP verbs) on those resources such as GET, POST, and so on to be shared. So, we may be happy to share our headlines, but not our login validation scripts.

Consuming the JSON feed

JSON has certainly established itself as the modern web data format, being lightweight to both produce and consume. To explore the JSON feature from end to end, we will detour briefly from the server-side and return to the client-side Dart in order to exercise the blog's JSON data feed. For this, take a look at the following code snippet:

Open the example project BlogJsonClient of this chapter. This a simple web project which acts as a client to the Blog server JSON feed. For this client to operate, the blog server must also be running.

void main() {
var jsonSrc = "http://127.0.0.1:8080/feed.json";  
 HttpRequest.getString(jsonSrc).then((String data) {
    List decoded = JSON.decode(data);
    decoded.forEach((post) {
      querySelector('#output').children.add(new LIElement()
        ..append(new AnchorElement()
          ..href = post['url']
          ..text = "${post['date']} ${post['title']}"));
    }); //for
  }); //then
}

The consumer of the JSON feed does not need to be aware of the CORS settings in any way. It simply makes an HTTP request to the appropriate URL to receive the JSON data or other resource. The request must meet the CORS requirements, such as the origin or HTTP verb to receive the desired response. Let's take a look at the following screenshot:

Consuming the JSON feed

Here, the HttpRequest class has a static method to return a remote resource as Future<String>, which is handled asynchronously in the then clause.

JSON is then iterated and the LI elements (List Items) are added to the DOM structure of the web page.

主站蜘蛛池模板: 文成县| 镇宁| 祁东县| 云霄县| 霍山县| 兰考县| 邵东县| 江西省| 博罗县| 义马市| 义马市| 专栏| 南皮县| 措美县| 昌宁县| 柳州市| 新乐市| 定安县| 九江县| 民丰县| 曲松县| 隆子县| 五台县| 东明县| 当雄县| 交口县| 长宁区| 大冶市| 克拉玛依市| 临武县| 家居| 临澧县| 茶陵县| 秦安县| 太谷县| 常州市| 延寿县| 旌德县| 临澧县| 原平市| 泾阳县|