Blackout
Blackout

Reputation: 157

Start dart application from Server and load elements

I'm new in dart's programming and I'm building a dart app and I would like to start it from the server side. Like loading my homepage when I enter the url of my webpage.

On my server side I have this code that I took from tutorials from dart's webpage:

var server;

  try{
    server = await HttpServer.bind(InternetAddress.LOOPBACK_IP_V6, 4040);
  }catch(e){
    print("Couldn't bind to port 4044: $e");
    exit(-1);
  }
  await for(HttpRequest req in server){
    var file = new File('index.html');

    if(await file.exists()){
      print("Serving index.html.");
      req.response.headers.contentType = ContentType.HTML;
      try{
        await file.openRead().pipe(req.response);
      }catch(e){
        print("Couldn't read file: $e");
        exit(-1);
      }
    }else{
      print("Couldn't open index.html");
      req.response..statusCode = HttpStatus.NOT_FOUND..close();
    }
  }

But now my problem is about the client side, my elements are not loading, like css, images, etc.

You can see the appearance here

I think that I need to set something at my server side to load that. What is it?

Upvotes: 1

Views: 81

Answers (1)

Steven Roose
Steven Roose

Reputation: 2769

Using the core dart:io methods for serving files is often not the easiest way. Take a look at shelf, f.e. It's a really neat framework for creating server applications that has a lot of plugins and extensions for middleware etc.

In your case, it seems like you just want to serve static content. I'd suggest you use shelf_static. It would go like this:

import 'package:shelf/shelf_io.dart' as io;
import 'package:shelf_static/shelf_static.dart';

void main() {
  var handler = createStaticHandler('your-web-directory/',
      defaultDocument: 'index.html');

  io.serve(handler, InternetAddress.LOOPBACK_IP_V6, 4040);
}

Upvotes: 1

Related Questions