Question

This question is kind of a duplicate of HTTPRequest.request with sendData, can't seem to get this to work, but I've got some more information now. The goal here is to send a GET request with query parameters attached. I initially tried to send my request as such:

HttpRequest request = new HttpRequest();

request.open("GET", _url, async:true);
request.onError.listen(_onLoadError, onError: _onLoadError);
request.send(sendData);

Where sendData is a String following the normal format for query parameters (?myVariable=2&myOtherVariable=a, etc), since this is the ultimate goal here. The request gets sent, but I never see any additional data (sendData) go with it in any monitoring tools (I'm using Charles). I then tried:

HttpRequest request = new HttpRequest();

request.open("GET", _url + sendData, async:true);
request.onError.listen(_onLoadError, onError: _onLoadError);
request.send();

So now I'm just attaching the query string to the url itself. This works as intended, but is far from elegant. Is there a better solution?

Was it helpful?

Solution 2

According to the W3 XMLHttpRequest Specification:

(In the send() method) The argument is ignored if request method is GET or HEAD.

So simple answer to this question is no. sendData cannot be appended to a GET request, this is by XMLHttpRequest specification and not a limitation of Dart.

That said, for requests like this it may be more readable and idiomatic to use HttpRequest.getString

HttpRequest.getString(_url + sendData).then((HttpRequest req) {
    // ... Code here
}).catchError(_onLoadError);

OTHER TIPS

On a GET request you always add the query string to the URL? When you create the Uri you can pass in a map with the query parameters if you find this more elegant.

Map query = {'xx':'yy', 'zz' : 'ss'};
String url = "http://localhost:8080/myapp/signinService";

Uri uri = new Uri(path: url, queryParameters : query);

HttpRequest.getString(uri.toString().then((HttpRequest req) ...

If you want to generate a valid URL from url (String) + query parameters (Map) , you can do the following :

 Uri uri = Uri.parse(url).replace(queryParameters: parameters);
 String finalURL = uri.toString();

url is a String and parameters is a Map

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top