繁体   English   中英

反应本机JWT-auth错误获取API

[英]react Native JWT-auth Error fetching api

React Native JWT-auth错误获取API

我试图通过使用jwt-auth通过以下方法获取用户详细信息。

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();
    }
}

并得到错误:-

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

如果有人知道,请帮助。

如果您的API使用的是基本身份验证,则需要添加用户名和密码作为身份验证标头

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();
    }
}

我认为您已经不再需要答案了,因为已经有一年了,发布此问题,如果还有其他人需要

如React Native的网络选项卡中所示,您需要将数据传递下面的标头中的 主体JWT令牌中 ,这对我有用,因此请查看并更新是否有任何问题

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();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM