0

I am trying to make a login screen for my react native app, but I can't get authentication token from my web api.

I try it with postman, and I can obtain the token.

I tried fetch api and adios for posting, no success.

This is my fetch code

   fetch("https://ahmetkocadogan.a2hosted.com/token", {
    method: "POST",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: JSON.stringify({
      grant_type: "password",
      deviceId: "ahmet",
      username: "ahmet",
      password: "123456",
    })
  }).then(response => {console.log(response);})
    .catch(error => {
      console.log(error);
    });
  }

My api token url is: https://ahmetkocadogan.a2hosted.com/token

in postman, I add headers as Accept - application/json, Content-Type - application/x-www.form.urlencoded

and body : grant_type - password , username - ahmet , password - 123456 , deviceId - ahmet

And I get the token from postman.

Any ideas? What is wrong with my fetch code?

1 Answer 1

2

I solved it with using fetch from react native, and changed the creation of my request header.

  var headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded'
  }
  var details = {
    'username': 'ahmet',
    'password': password,
    'grant_type': 'password',
    'deviceId': 'ahmet'
  };
  var formBody = [];
  for (var property in details) {
    var encodedKey = encodeURIComponent(property);
    var encodedValue = encodeURIComponent(details[property]);
    formBody.push(encodedKey + "=" + encodedValue);
  }
  formBody = formBody.join("&");
  console.log('fetch baslıyor');
  let result = await fetch(API_ROOT_URL + '/token', {
     method: 'POST',
     headers: {
       'Accept': 'application/json',
       'Content-Type': 'application/x-www-form-urlencoded'
     },
     body: formBody
   });
  let resultJson = await result.json();

Now it works.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.