ahmet kocadogan
ahmet kocadogan

Reputation: 137

React Native - Can't get token from asp.net web api

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?

Upvotes: 0

Views: 994

Answers (1)

ahmet kocadogan
ahmet kocadogan

Reputation: 137

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.

Upvotes: 2

Related Questions