Serving content dynamically using the directory parameter for GET requests – shelf package dart


The code snippets below come from a server serving a get request

Server snippets


  io.serve(handler, InternetAddress.LOOPBACK_IP_V4, 8080).then((server) {
    print('Listening on port 8080');
  }).catchError((error) => print(error));


Router routes = new Router()
                      ..get('/newest', handler.handleNewest)
                      ..get('/anonymous', handler.handleAnonymousGetRequest)
            '/anonymous', handler.handleAnonymousPostRequest);


shelf.Response handleNewest(shelf.Request request){
  print('got request for newest');
  return new shelf.Response.ok('sample content later fetched form db');

On a click event I also run this code in a client app.

void makeRequestNewest() {
  String path = '';
    .then((String newestContent){
  .catchError((Error error){
    post_list.appendText('an error occurred: ' + error.toString());

unfortunately the getString is not successful. The catchError is run and results in an error occurred: Instance of '_XMLHttpRequestProgressEvent'.
Also in the ToolsOutput command line of the Dart Editor I get [web] GET /newest => Could not find asset linkShepherdClient|web/newest.. This is correct, because that directory does not exist. I thought I can use the directory as a parameter to run the correct handler, and return the correct value in the .ok(), but it doesn’t seem so. Does this mean I can not fetch the data from any source using the GET request, because it will always try to actually get it from this directory on the server?

Edit: code example using http package. (not working)

import 'package:http/http.dart' as http;
import 'package:http/browser_client.dart';

void makeRequestNewest() {
  String path = '';
  var client = new BrowserClient();
    post_list.appendText('response status: ${response.statusCode}');
    post_list.appendText('Response body: ${response.body}');

An answer using additional packages like the http package is also very welcome.


I figured it out. I tried to access resources from a different domain (localhost:8080 and not localhost:8080/newest). This requres setting CORS header in the shelf.response. This is done for example like that

shelf.Response.ok('Message returned by handleNewest later fetched by db', headers: CORSHeader);

where CORSHeader is set to

const Map<String, String> CORSHeader = const {'Access-Control-Allow-Origin': '*'};

If you want to have access to the content from any domain. You can also replace the star with the domain you want to restrict the access to.

Answered By – Lukasz

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *