我正在使用React native构建登录应用程序。对于auth,我使用的是spring boot应用程序。
这是用例。
-
-
使用fetch API向服务器响应本机发送请求。
-
如果令牌对象返回,则登录(用户名/密码)是正确的。
-
代码如下:
import { dologin,getUser } from "../../API";
和登录handler
handleLogin = () => {
const { username, password } = this.state
if (username.length == 0 || password.length == 0){
this.setState({
errorMessage: 'Login and password is required.',
loginProcessing: false,
});
} else {
this.setState({errorMessage: null});
dologin(username, password).then(accessToken => {
if(!accessToken.state){
this.setState({
errorMessage: accessToken.data,
loginProcessing: false,
});
return null;
} else{
return accessToken.data;
}
});
}
}
获取API
//get user by token
export const getUser = (token) => {
if(token == null) return null;
return fetch('http://localhost:8080/api/user/get', {
method: 'GET',
headers: {"Authorization": "Bearer " + token}
}).then((response) => {
console.log(response.json());
return response.json();
}).catch((err) => {
console.log(err);
})
}
export const dologin = (username, password) => {
var details = {
username: username,
password: password,
grant_type:'password'
};
var formBody = [];
for (var property in details) {
var encodedKey = encodeURIComponent(property);
var encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
return fetch('http://localhost:8080/oauth/token', {
method: 'POST',
headers: {
"Authorization": "Basic " + btoa("enrecover:EsTEsBDETSEWAvAWcsI"),
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
body: formBody.join("&")
}).then(res => {
if(res.status === 200){
return {status: true, data:res.json() }
} else {
return {status: false, data:"Invalid username or password." }
}
})
}