0

So this is the curl I use for testing:

curl http://MYIP:5000/register   -H 'Content-Type: application/json' -d '{"username": "test","password": "test","email":"test@test.test","passwordAgain": "test"}'

And this is the code from the app:

String url = "http://MYIP:5000/register";
var response = await http.post(Uri.parse(url), body: {
      "username": "test",
      "password": "test",
       "email": "test@test.test",
       "passwordAgain": "test"}
    );

The curl request is working, the app code says something is wrong (400 Bad Request).

shb
  • 5,957
  • 2
  • 15
  • 32
Daryl
  • 1

1 Answers1

0

You're not passing -H 'Content-Type: application/json'

Set the following headers

String url = "http://MYIP:5000/register";
Map<String, String> headers = {
      'Content-type': 'application/json',
      'Accept': 'application/json',
    };

Map<String, String> body = {
       "username": "test",
       "password": "test",
       "email": "test@test.test",
       "passwordAgain": "test"
     };

var response = await http.post(
      Uri.parse(url),
      headers: headers,
      body: json.encode(body)
  );
shb
  • 5,957
  • 2
  • 15
  • 32
  • 1
    Thanks, still not working but with this I found that I even need to use jsonEncode on the body. Now the status code is 409. – Daryl Dec 27 '21 at 17:45
  • 1
    What error do you see in the server's logs? (And correct, you need to json encode the body (if the server is expecting json), otherwise `http` will *form* encode the map for you.) – Richard Heap Dec 27 '21 at 17:51
  • Only "already exists" but the response is what I need. I don't understand why is the response good but the status codes are wrong (its still 409 but i need either 200 or 201) – Daryl Dec 27 '21 at 18:08
  • Your post request is working, the response code seems like a server side thing, more https://stackoverflow.com/q/3825990/6207294. Check if the curl also returns 409 – shb Dec 27 '21 at 18:18
  • I suspect that your server is telling you that user "test" already exists, so you can't register it again. Your server is telling you "already exists" and 409 is saying "conflict" (your request cannot be completed because it conflicts with, one might imagine, the existing user called "test"). – Richard Heap Dec 27 '21 at 22:35
  • with the same curl code I get 200 after the user already exists, and I need that on the app. – Daryl Dec 28 '21 at 10:28