0
votes

I'm writing a client REST in Flutter/Dart that should manage some data from a REST Server (Java server). The client works fine if compiled for Android , no problem at all. But when it is compiled for Chrome ( Javascript ) there are many problems, like this: when I try to make an HTTP PUT request the client seems to take an unknown error without sending the request to the server.

The strange thing is that this problem is only on the verb PUT, the verb POST works fine (but I stil not tried with PATCH/ DELETE). So it seems a bug on the internal http library when used the verb PUT instead of POST. http: 0.10.0

Here the code:

 void _sendRequest() async {
       try {
          print('Send Request : ');
          //   String url = "http://10.0.2.2:8080/v2/account";
          String url = "http://localhost:8080/v2/account";
          Map<String, String> headers = new HashMap();
          headers['Accept'] = 'application/json';
          headers['Content-type'] = 'application/json';

          Http.Response response = await Http.put(url,
              headers: headers,
              body: jsonEncode({
              "description": "string",
              "id": 25,
              "name": "11112",
              "password": "seesfs"
           }),
           encoding: Encoding.getByName('utf-8'));

          print('Response status: ${response.statusCode}');
          print('Response body: ${response.body}');
       }catch(error) {
         print("${error?.toString()}");
       }
      }

As you can see, I use the localhost address when I use the web client, and 10.0.2.2 when I use the android VM. The same code works when compiled with android and does not when javascript. Any idea? Do you have encountered the same problem?

Here follows the sample test project:

name: accounts_client_http description: A new Flutter project.

version: 1.0.0+1

environment: sdk: ">=2.1.0 <3.0.0"

dependencies: http:^0.12.0+4 flutter: sdk: flutter

dev_dependencies: flutter_test: sdk: flutter

flutter: uses-material-design: true

Here follows the flutter doctor

 flutter doctor
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel beta, v1.14.6, on Linux, locale it_IT.UTF-8)

[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.2)
[✓] Chrome - develop for the web
[✓] Android Studio (version 3.5)
[✓] IntelliJ IDEA Community Edition (version 2019.3)
[✓] VS Code (version 1.43.0)
[✓] Connected device (2 available)

• No issues found!
1

1 Answers

0
votes

The problem is solved in this way: in the server side I added the allowed methods to CORS Registry:

@Configuration public class WebConfig implements WebMvcConfigurer {

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**").allowedMethods("PUT", "GET", "POST", "PATCH");
}

}