【问题标题】:Getting 'post : 400 bad request in react得到'post : 400 bad request in react
【发布时间】:2020-06-26 15:42:27
【问题描述】:

这里我有注册表单。我有用户名、密码字段。我使用rest api将数据发送到服务器。我不能直接发送数据。我必须加密数据并将令牌发送到服务器。我使用 Jwt 发送数据。为了生成令牌,我安装了 npm i json-web-token 包。我想,我在使用 jwt 令牌时犯了错误。但我无法修复它。

 export class SignUp extends Component {
  constructor() {
    super();
    this.state = {
        username: '',
        Password: '',
        confirmPassword: '',
        token: ''

    }

    this.username = this.username.bind(this);
    this.Password = this.Password.bind(this);
    this.confirmPassword = this.confirmPassword.bind(this);
    this.SignUp = this.SignUp.bind(this);
}

username(event) {
    this.setState({ username: event.target.value })
}

Password(event) {
    this.setState({ Password: event.target.value })
}

confirmPassword(event) {
    this.setState({ confirmPassword: event.target.value })
}
SignUp(event) {

    var jwt = require('json-web-token');
    var secret = "topsecret";
    var payload = {
        "iss": "my_issurer",
        "aud": "World",
        "iat": 1400062400223,
        "username": this.state.username,
        "Password": this.state.Password,
    };
    const token = jwt.encode(secret, payload)
    console.log("token", token);
    const dtoken = jwt.decode(secret, token.value);
    console.log("dtoken", dtoken);


    fetch('url', {
        method: 'post',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        },

        body:  token.value


    }).then((Response) => Response.json())

        .then((Result) => {

            if (Result.Status === 'Success')

                this.props.history.push("/Home");
            else
                alert('Sorrrrrry !Account has not been created!!!!!')
        })
    }
  }

render() {

    return (

        <div>
            < form >
                < div class="row">
                    < div  >Sign Up </div >
                </div >

                < input type="text" onChange={this.username} placeholder="Enter username" />
                <br /><br />
                < input type="password" onChange={this.Password} placeholder="Enter Password" />
                <br /><br />
                <input type="password" onChange={this.state.confirmPassword} placeholder="ReEnter Password" />
                <br /><br />
                < Button onClick={this.SignUp}> Create Account</Button >
                <br /><br />
            </form >


        </div >
    );
}

}

提前致谢。

【问题讨论】:

    标签: reactjs rest jwt


    【解决方案1】:

    您需要在服务器端使用 JWT 库,而不是在客户端。

    当您有用户注册时,该用户会将用户名、密码和其他信息发送到您的服务器,然后您需要使用 JWT 库根据您的密钥和有效负载为该用户生成令牌。

    然后令牌将在客户端发送回此用户,此用户需要将令牌保存在本地存储或 cookie 中。如果该用户需要访问您的安全 REST API,她/他需要在请求中发送带有令牌的授权标头。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2021-09-26
      • 1970-01-01
      • 1970-01-01
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      相关资源
      最近更新 更多