Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dio sends empty form body in POST request #88

Closed
neeraj87 opened this issue Oct 30, 2018 · 23 comments
Closed

Dio sends empty form body in POST request #88

neeraj87 opened this issue Oct 30, 2018 · 23 comments

Comments

@neeraj87
Copy link

I am sending the following POST request to my node.js server:

import 'package:dio/dio.dart';
import 'dart:io';

print("--- userData: $userData"); // its a Map<String, dynamic>
Dio dio = new Dio();
dio.options.headers = {
  'Authorization': 'Bearer ' + prefs.getString("TOKEN"),
  'uuid': _uuid
};
dio.options.contentType = ContentType.parse("application/json");

FormData formData = new FormData.from(userData);

print("--- updated user info: $formData");

Response response = await dio.post("https://myapi.com/api/user/update", data: formData);

if(response.statusCode == 200) {
  Scaffold.of(context).showSnackBar(new SnackBar(
    content: new Text("User Info Updated"),
  ));
} else {
  Map<String, dynamic> _responseMap = json.decode(response.data);
  Scaffold.of(context).showSnackBar(new SnackBar(
    content: new Text(_responseMap['message']),
  ));
}

where the userData and formData print statement prints out something like this:

{
  first_name: John,
  last_name: Doe,
  age: 56,
  gender: Male,
  phone: 8888888888,
  email: [email protected],
  others: some text and some other stuff
}

However on my server side I get an empty body. However when I do the same thing with Flutter's http:

Map<String, String> headersMap = {
  'Content-Type' : 'application/json',
  'Authorization' : 'Bearer ' + prefs.getString("TOKEN"),
  'uuid': _uuid
};

http.post(
    'https://myapi.com/api/user/update',
    body: json.encode(userData),
    headers: headersMap
).then((http.Response response){
  if(response.statusCode == 200) {
    Scaffold.of(context).showSnackBar(new SnackBar(
      content: new Text("User Info Updated"),
    ));
  }
});

I receive the data on server side.

I even tried the Dio code by commenting the dio.options.contentType line but I still get empty request body. What is going on? What am I missing?

@wendux
Copy link
Contributor

wendux commented Oct 31, 2018

you should send post request directly as follows:

Response response = await dio.post("https://myapi.com/api/user/update", data: userData);

In your situation, you shouldn't use FormData,because using FormData will lead the dio to set request contentType as "multipart/form-data"。

@neeraj87
Copy link
Author

Thanks, it worked.

@agnoam agnoam mentioned this issue Feb 9, 2019
@HacktorDevelopers
Copy link

you should send post request directly as follows:

Response response = await dio.post("https://myapi.com/api/user/update", data: userData);

In your situation, you shouldn't use FormData,because using FormData will lead the dio to set request contentType as "multipart/form-data"。

But what about the case of sending file to the server using post request

@tharwatsamy
Copy link

you should send post request directly as follows:

Response response = await dio.post("https://myapi.com/api/user/update", data: userData);

In your situation, you shouldn't use FormData,because using FormData will lead the dio to set request contentType as "multipart/form-data"。

But what about the case of sending file to the server using post request

u can use FormData but don't specify a content type if u specified a content type the body will be empty I tried it and it worked that way

@Izudinalqasam
Copy link

Izudinalqasam commented Feb 2, 2021

hi guys, i face this issue, i have tried the ways above but none of them can resolve my issue

this is my setup and data

  • Dio
    ` static final option = BaseOptions(
    baseUrl: AppConfig.instance.baseUrl, connectTimeout: 50000, receiveTimeout: 50000);

    static final interceptor = PrettyDioLogger(
    requestHeader: true,
    requestBody: true,
    responseBody: true,
    responseHeader: false,
    error: true,
    compact: true,
    maxWidth: 90);

    final Dio dio = Dio(option)
    ..interceptors.add(interceptor);`

  • method send
    Future<Response> postFileDigital( FormData formFileDigital, String token) async { dio.options.headers['authorization'] = "Bearer " + token; return await dio.post(FILE_DIGITAL_UPLOAD_URL, data: formFileDigital); }

  • this is form
    FormData.fromMap(<String, dynamic>{ "attendance_date": currentDates.first, "check_in": currentDates[1].substring(0, 8), "lat": geoLocation.latitude.toString(), "lng": geoLocation.longitude.toString(), "status_health": "HEALTHY", // "photo": await MultipartFile.fromFile(file.path) }

    i have been log the request data is exist when sending data to server but the server read empty data.
    anyone can help me ?

    my dio version => dio: ^3.0.9

@RaoSaqib7860
Copy link

RaoSaqib7860 commented Feb 2, 2021 via email

@lalaviiie
Copy link

Hi, i face this issue, @Izudinalqasam did you solve it?

@RaoSaqib7860
Copy link

RaoSaqib7860 commented Feb 11, 2021 via email

@RaoSaqib7860
Copy link

RaoSaqib7860 commented Feb 11, 2021 via email

@lalaviiie
Copy link

i am trying to upload images using dio FormData, the request body containing two parts:
-images: array of images
-element: element information (json)
when i log my FormData the data exist, but it seems the server is recieving an empty data..
i got 400 (bad request) with message : required request part 'element' is not present

@Izudinalqasam
Copy link

@mayma93 not yet, for that case i use alternative http package and it work fine coexisting with dio

@lalaviiie
Copy link

lalaviiie commented Feb 12, 2021

@Izudinalqasam can you share your code please? with http package

@RaoSaqib7860
Copy link

RaoSaqib7860 commented Feb 12, 2021 via email

@RaoSaqib7860
Copy link

RaoSaqib7860 commented Feb 12, 2021 via email

@RaoSaqib7860
Copy link

RaoSaqib7860 commented Feb 12, 2021 via email

@lalaviiie
Copy link

i used MultipartFile.fromFile and i got Unsupported Media Type.. he use the default content type application/octet-stream

@RaoSaqib7860
Copy link

RaoSaqib7860 commented Feb 12, 2021 via email

@RaoSaqib7860
Copy link

RaoSaqib7860 commented Feb 12, 2021 via email

@RaoSaqib7860
Copy link

RaoSaqib7860 commented Feb 12, 2021 via email

@lalaviiie
Copy link

Future createElement(element element, List images) async {
FormData formData = FormData();

if (images != null) {
  for (File item in images)
    formData.files.addAll([
      MapEntry(
          "images",
          await MultipartFile.fromFile(item.path,
              filename: item.path.split('/').last)),
    ]);
}
formData.fields.add(MapEntry("element", element.toString()));
final response = await _dio.post('/api/element/', data: formData);

}

the output: 415
{"timestamp":1613122248141,"status":415,"error":"Unsupported Media Type","message":"Content type 'application/octet-stream' not supported","path":"/api/element/"}

@RaoSaqib7860
Copy link

RaoSaqib7860 commented Feb 12, 2021 via email

@huynguyennovem
Copy link

Just tried with this and success:

data: json.encode(null)

@MostafaSolimanMO
Copy link

Future createElement(element element, List images) async { FormData formData = FormData();

if (images != null) {
  for (File item in images)
    formData.files.addAll([
      MapEntry(
          "images",
          await MultipartFile.fromFile(item.path,
              filename: item.path.split('/').last)),
    ]);
}
formData.fields.add(MapEntry("element", element.toString()));
final response = await _dio.post('/api/element/', data: formData);

}

the output: 415 {"timestamp":1613122248141,"status":415,"error":"Unsupported Media Type","message":"Content type 'application/octet-stream' not supported","path":"/api/element/"}

I am having this issue with dio ^5.3.2
Did you solve it?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants