【发布时间】:2021-08-06 00:32:43
【问题描述】:
我正在尝试在我的反应应用程序中实现基本身份验证。我在标题中发送了email 和password,同时向我的/users 端点发出GET 请求,并根据响应决定登录是否成功。如果登录成功(即用户存在于端点),那么我们推送到<projects> 组件。但我希望用户只有在他是有效用户的情况下才能访问/projects url。如何应用私有路由
这就是我的登录页面代码的样子 函数登录(){
const [password, setPassword] = React.useState("");
const [email, setEmail] = React.useState("");
const [err, setErr] = React.useState(null);
const history = useHistory();
const handleSubmit = async (event, password, email) => {
event.preventDefault();
var myHeaders = new Headers();
myHeaders.set('Authorization', 'Basic ' + encode(email + ":" + password));
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
let response;
try {
response = await fetch (`${APIlink}/users`, requestOptions)
} catch (err) {
setErr("Incorrect Password. Please Retry.");
return;
}
const result = await response.text();
console.log(result);
const json = JSON.parse(result);
console.log(json);
console.log(response);
if (response.status===200) {
setErr(null);
history.push("/Projects"); //valid user is redirected but /Projects is accessible by just
//writing the url as well
} else {
setErr(json.error);
console.log(json.error);
}
};
这是发送正确凭据后我的 json 对象的外观 (email: abc, password: test)
{
"password": "test",
"rollno": "18am200",
"email": "abc",
"name": "mkyong",
"user-uid": "7e7199247de1125a6dc1518dd78ba554"
}
这就是我的回复的样子
Response { type: "cors", url: "{APIlink/users", redirected: false, status: 200, ok: true, statusText: "OK", headers: Headers, body: ReadableStream, bodyUsed: true }
App.js
function App() {
return (
<div >
<HashRouter basename ='/'>
<Switch>
<Route path="/" component = {Home} exact/>
<Route path="/Login" component = {LogIn}/>
<Route path="/Register" component = {Register}/>
<Route path="/Projects" component = {ProjectComponent} />
<Route path="/Application" component = {Project2Component} />
<Route path="/Demo1" component = {Project3Component} />
<Route path="/Demo2" component = {Project4Component} />
</Switch>
</HashRouter>
</div>
)
}
export default App
【问题讨论】:
-
请添加您的
App.jsx或index.js文件的一些代码,或您已映射路线的sn-p,例如<Route path={route.path} component={LoginComponent} /> -
@bonnopc 我已经添加了 App.js 代码,除了主页和登录页面,其他所有内容都应该只有登录用户才能访问。
-
您需要某种支持用户会话和验证的身份验证架构,例如 cookie 或 JWT,这太长而无法包含在单个 SO 答案中。我建议你搜索一些相关的文章来解释。
标签: javascript reactjs react-hooks fetch basic-authentication