【发布时间】:2020-11-11 14:25:18
【问题描述】:
我正在使用带有 Node & express 的 React 并使用本地护照和护照进行身份验证,我想知道如何保护 React 中的路由,我的意思是我只想在用户通过身份验证时才显示组件,否则我希望它在登录页面上重定向。
就我而言,我想保护 Notes 路线, 我正在尝试的方法根本不起作用......
我的反应代码
import React from 'react';
import { Switch, Route, Redirect } from 'react-router-dom';
import axios from 'axios';
import Register from './Components/Register';
import Login from './Components/Login';
import Notes from './Components/Notes';
function App () {
//Function to check authentication from server
const checkAuth = () => {
axios.get('http://localhost:8000/notes', { withCredentials : true })
.then(res => res.data)
}
return (
<Switch>
<Route exact path='/' component={Register} />
<Route exact path='/login' component={Login} />
<Route exact path='/notes' render={() => {
return checkAuth()? (
<Notes />
) : (
<Redirect to="/login" />
)
}} />
</Switch>
);
};
export default App;
还有我的服务器端代码
//Notes Page
router.get('/notes', (req, res) => {
if(req.isAuthenticated()) {
res.send(req.user.email);
}else{
res.send(false);
}
};
【问题讨论】:
标签: javascript node.js reactjs express passport.js