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

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.

主站蜘蛛池模板: 慈利县| 巫溪县| 肇东市| 甘南县| 平泉县| 迁西县| 长岭县| 色达县| 巴马| 华安县| 石城县| 金寨县| 慈利县| 丽水市| 逊克县| 兰州市| 合水县| 宜兰县| 邮箱| 玉树县| 海南省| 新建县| 临城县| 南平市| 扶风县| 琼中| 晋宁县| 华宁县| 芦溪县| 台南市| 丰城市| 吴忠市| 威远县| 建宁县| 外汇| 舞钢市| 盖州市| 黔东| 扬州市| 香港 | 漠河县|