1

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?

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Lukasz
  • 2,257
  • 3
  • 26
  • 44

1 Answers1

2

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);
    });
  });
}
Danny Tuppeny
  • 40,147
  • 24
  • 151
  • 275
  • Thanks @DannyTuppeny. Unfortunately it still doesn't work. I added `print('test')` under `virDir.serveRequest(request);` and every time i click refresh it writes test, but it does not serve the webclient. Any other ideas? – Lukasz Oct 21 '14 at 06:27
  • Are you giving it a part to a file, or expecting it to default to something (like index.htm)? – Danny Tuppeny Oct 21 '14 at 06:41
  • @Lukasz See updated answer for how to get `/` to map to `/index.html`, assuming that might be what's going wrong. – Danny Tuppeny Oct 21 '14 at 07:55
  • Thanks @DannyTuppeny. Could you please add `..allowDirectoryListing = true` after `virDir = new VirtualDirectory(r"E:\DartProject\WebClient\web")`, this is required for it to work correctly. – Lukasz Oct 21 '14 at 12:08
  • @Lukasz Done! I actually removed that assuming it wouldn't be needed trying to keep the code more like your own! Doh! – Danny Tuppeny Oct 21 '14 at 12:13