1

React Native JWT-auth Error fetching api

I am trying to fetch user detail by using jwt-auth, by following method.

login() {
    alert(this.state.UserName);
    fetch (Api+''+'/wp-json/jwt-auth/v1/token',{
        method: "POST",
        username: this.state.UserName,
        password: this.state.Password
    }).then((response) => response.json())
      .then((responseData) =>{
          console.log("LoginData:-" + JSON.stringify(responseData));
       }).done();
    }
}

and getting error:-

{
    "code":"[jwt_auth] empty_username",
    "message":"<strong>ERROR</strong>: The username field is empty.",
    "data":{"status":403}
}

If anyone Knows Please help.

2 Answers 2

1

I dont think you need the answer anymore as its been an year posting this question, Still if anyone else need

As shown in the networking tab of React Native You need to pass data into body and JWT token in headers like below, this is working for me so have a look and update if there is any problem into this

login(){
    fetch(Api+''+'/wp-json/jwt-auth/v1/token', {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'JWT '+<token> // There will be different type of authorization like Bearer, JWT, Basic
      },
      body: JSON.stringify({
        username: this.state.UserName,
        password: this.state.Password
      }),
    })
    .then((response) => response.json())
    .then((responseData) => {
        console.log("LoginData:-" + JSON.stringify(responseData));
    }).done();
}
Sign up to request clarification or add additional context in comments.

Comments

0

If your API is using basic Authentication you need to add username and password as a Authentication header

Example

const base64 = require('base-64');
login() {
    alert(this.state.UserName);
    fetch (Api+''+'/wp-json/jwt-auth/v1/token',{
        method: "POST",
        headers: {
            'Authorization', 'Basic ' + base64.encode(this.state.UserName+ ":" + this.state.Password)
        }
    }).then((response) => response.json())
      .then((responseData) =>{
          console.log("LoginData:-" + JSON.stringify(responseData));
       }).done();
    }
}

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.