Book Image

DART Cookbook

By : Ivo Balbaert
Book Image

DART Cookbook

By: Ivo Balbaert

Overview of this book

Table of Contents (18 chapters)
Dart Cookbook
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Receiving data on the web server


In the previous recipe, we made a client app that sends its data to a web server in JSON format. In this recipe, we will make the web server that receives this data step by step, possibly process it, and then send it back to the client. You can find the code in the script server\webserver.dart in the project post_form.

How to do it...

Perform the following steps to make this work:

  1. The following is the code that starts the web server:

    import 'dart:io';
    
    const HOST = '127.0.0.1';
    const PORT = 4040;
    
    void main() {
      HttpServer.bind(HOST, PORT).then(acceptRequests, onError: handleError);
    }
  2. The acceptRequests function describes how the web server handles incoming requests based on their method as follows:

    void acceptRequests(server) { 
      server.listen((HttpRequest req) {
        switch (req.method) {
          
    case 'POST':
          handlePost(req);
          break;
          case 'GET':
          handleGet(req);
          break;
          case 'OPTIONS':
          handleOptions(req);
          break;
     ...