我的目标是创建一个运行json Rest服务的React JS登录页面。在Postman中,当我输入服务的URL时,将其设置为以POST运行并在主体中输入以下JSON: {username:" myUserName",密码:" myPassword"} ...返回一个令牌。所以在我的fetch子句中,我使用JSON.stringify将用户名和密码传递给服务器。
我刚接触Fetch with react,所以我的问题是,我如何开始验证各种用户,只使用带有fetch的react JS?我假设,我是在我的Fetch子句的第二个内写我的逻辑吗?
目前,我的网页接受任何凭据,并在点击提交按钮后将用户路由到目标网页。我有一个包含fetch的函数,现在一旦点击onSubmit按钮就调用了fetch函数,现在它会抓取令牌。
这是我的代码:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import './Login.css';
import { withRouter } from 'react-router-dom';
class Login extends Component {
constructor() {
super();
this.state = {
data: [],
username: "",
password: "",
token: "",
};
} //end constructor
componentWillMount() {
}
componentDidMount() {
this.fetchData();
}
fetchData() {
fetch('http://theapi/api/auth', {
method: 'POST',
headers: {
'Content-type': 'application/json',
},
body: JSON.stringify({
username: 'myUserName',
password: 'myPassword',
Authorization: 'TheReturnedToken',
})
}) /*end fetch */
.then(results => results.json())
.then(data => this.setState({ data: data })
)
}
//request the token
requestAccessToken(data) {
const loginInfo = '${data}&grant_type=password';
return fetch('${API_URL}Token', {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json',
}),
body: loginInfo,
})
.then((response) => response.json());
}
//authenticate request
requestUserInfo(token) {
return fetch('${API_URL}api/participant/userinfo', {
method: 'GET',
headers: new Headers({
Authorization: 'Bearer ${token}',
}),
})
.then((response) => response.json());
}
change = (e) => {
this.setState({
[e.target.name]: e.target.value
});
}; //end change
onSubmit = (e) =>{
this.fetchData();
e.preventDefault();
//console.log(this.state);
this.setState({
username: "",
password: "",
});
this.props.history.push('/landing');
};
render() {
console.log(this.state.data);
return (
<div>
<div className="loginContainer">
<h2>Member Login</h2>
<form>
<input
id="username"
name="username"
placeholder="User Name"
value={this.state.username}
onChange={e => this.change(e) }
className="form-control"
/> <br />
<input
id="password"
name="password"
type="password"
placeholder="Password"
value={this.state.password}
onChange={e => this.change(e) }
className="form-control"
/> <br />
<button onClick={e => this.onSubmit(e)} className="btn btn-primary">Submit</button>
</form>
</div>
</div>
);
}
}
export default withRouter(Login);
如何让我的表单开始验证各种用户?基本上,我试图让我的页面接受用户名和密码,如果两者匹配,然后将用户路由到登录页面。