Search code examples
dartdart-io

Serving sample website using dart


I just started learning dart, and what I wanted to do as practice is to serve the default web application with a simple webserver. I store the server at E:\DartProject\server and the web client at E:\DartProject\WebClient. Unfortunately I can't get the server to serve the webapp. The code for the webserver is

import 'dart:io';
import 'package:http_server/http_server.dart' show VirtualDirectory;


VirtualDirectory virDir = new VirtualDirectory("E:\DartProject\WebClient\web");

void main() {
  HttpServer.bind(InternetAddress.ANY_IP_V4, 80).then((server) {
    print("Serving at ${server.address}:${server.port}");
    server.listen((request) {
      virDir.serveRequest(request);
    });
  });
}

I'm always getting 404 errors. What do I do wrong?


Solution

  • The backslashes in your path may be being interpreted as escape characters?

    Try changing "E:\DartProject\WebClient\web" to r"E:\DartProject\WebClient\web", which will instruct Dart to interpret the whole string literally.

    You also need to configure a "default document" if you're expected / to serve up /index.html, for example.

    void directoryHandler(dir, request) {
      var indexUri = new Uri.file(dir.path).resolve('index.html');
      virDir.serveFile(new File(indexUri.toFilePath()), request);
    }
    
    void main() {
      virDir = new VirtualDirectory(r"E:\DartProject\WebClient\web")
        ..allowDirectoryListing = true
        ..directoryHandler = directoryHandler;
    
      HttpServer.bind(InternetAddress.LOOPBACK_IP_V4, 8080).then((server) {
        print("Serving at ${server.address}:${server.port}");
        server.listen((request) {
          virDir.serveRequest(request);
        });
      });
    }