2

I have a Post Request using fetch in react native, but I get a status code 400 for this, what is wrong with the code?

function sendRequest2() {
    fetch(`https://sandbox-api.dexcom.com/v2/oauth2/token`, {
      method: "POST",
      headers: {
        "Content-Type": "application/x-www-form-urlencoded",
      },
      body: JSON.stringify({
        code: "value1",
        client_id: "value2",
        client_secret: "value3",
        redirect_uri: "http://www.google.com",
        grant_type: "authorization_code",
      }),
    })
      .then((response) => {
        response.json();
      })
      .then((data) => {
        console.log(data);
      })
      .catch((err) => console.log("The error is: " + err));
  }
Santam
  • 123
  • 2
  • 9
  • can you try by not JSON.stringify the data? That step does not seems to be required. – TARJU Nov 12 '21 at 10:43
  • Remove the image, and then try to URLEncode the body instead of stringify. See here https://stackoverflow.com/a/63501847/1702612 – Bikas Nov 12 '21 at 12:02

2 Answers2

0

Check your content-type, replace it by :

headers: {
    "Content-Type": "application/json",
  },

helpfull link : application/x-www-form-urlencoded or multipart/form-data?

Romylussone
  • 773
  • 1
  • 8
  • 19
  • I did it. I am getting a status code of 415 – Santam Nov 12 '21 at 12:13
  • 1 - remove JSON.stringify as said above and define a variable object (containing your data ) oustside your body scope then set it to your body scope. retry , hoping it'll runing well.. – Romylussone Nov 15 '21 at 09:47
  • 2 - if it still same , i think something going wrong with your data datatype, so check them carefully. Good luck !! – Romylussone Nov 15 '21 at 09:52
  • I’m still facing this problem with application/x-www-form-urlencoded. Yeah, it’s openid oauth2 keycloak server required, so cannot change to other type. I code in reactjs, but still no luck. Any ideas? – bandungeuy Sep 26 '22 at 02:44
0

You can try by removing JSON.stringify

That would solve the issue

Moreover you have shared a lot of open information regarding your server openly.

You must either hide it or add some dummy values. Sharing such a secure data openly is not recommended in open community.

TARJU
  • 1,785
  • 1
  • 14
  • 16
  • I removed the JSON.stringify by still getting a status code 400 :( – Santam Nov 12 '21 at 12:52
  • what type of program is this? Is this node.js code? If so you would need some additional setting using body-parser ... here is example code from https://expressjs.com/en/resources/middleware/body-parser.html var express = require('express') var bodyParser = require('body-parser') var app = express() // parse application/x-www-form-urlencoded app.use(bodyParser.urlencoded({ extended: false })) // parse application/json app.use(bodyParser.json()) – TARJU Nov 15 '21 at 04:44