The code snippets below come from a server serving a get request
Server snippets
1)
io.serve(handler, InternetAddress.LOOPBACK_IP_V4, 8080).then((server) {
print('Listening on port 8080');
}).catchError((error) => print(error));
2)
Router routes = new Router()
..get('/newest', handler.handleNewest)
..get('/anonymous', handler.handleAnonymousGetRequest)
..post('/anonymous', handler.handleAnonymousPostRequest);
3)
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 = 'http://127.0.0.1:8080/newest';
HttpRequest.getString(path)
.then((String newestContent){
post_list.appendText(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 = 'http://127.0.0.1:8080/newest';
var client = new BrowserClient();
client.get(path)
.then((response){
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.