1

My Flutter http.post request is sending an empty body to my Node.js server. Here is my front-end code:

var response = await http.post(Uri.parse('$host/api/new'),
            body: {
              'id': '$id',
              'token': token
            });

The post is reaching my node.js server, but the body is an empty object. What am I doing wrong?

Page COW
  • 515
  • 13
  • 31

2 Answers2

2

Adding this to the post request fixed it for me:

headers: {
      HttpHeaders.contentTypeHeader: 'application/json',
    },

Then adding this around the body:

jsonEncode({ ... })

And importing this:

import 'dart:io';
Page COW
  • 515
  • 13
  • 31
0

Try following.

Include headers in request for back end to understand data being sent in json format, and encode data to json.

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

static final client = http.Client();

static Future<dynamic> someFunctionName() async {
  //parse URL
  var parsedUrl = Uri.parse(URL);
  // define headers
  Map<String, String> postHeaders = {"Content-Type": "application/json"};
  // json encode map
  encodedBody = json.encode({'id': '$id','token': token})
  // execute http post
  var response = await client.post(parsedUrl, headers: postHeaders, body: encodedBody);
  print('network_handler.dart - response.body = ${response.body}');
  return response;
}