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

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.

主站蜘蛛池模板: 新沂市| 麻栗坡县| 卢湾区| 昭苏县| 邢台市| 长春市| 杭锦后旗| 旌德县| 旌德县| 临西县| 孟连| 勐海县| 龙州县| 芜湖县| 乌拉特前旗| 庆云县| 平罗县| 湘潭市| 乌拉特后旗| 东海县| 屏边| 淅川县| 文成县| 拉萨市| 阿拉善左旗| 太白县| 南宁市| 永泰县| 新源县| 林州市| 九寨沟县| 富平县| 福州市| 壤塘县| 乌审旗| 蓬莱市| 江口县| 澄城县| 和田县| 台南市| 阿鲁科尔沁旗|