如何解决路由的登录和身份验证反应或服务器端
我正在尝试保护我在 React 页面上的表单路由。我在服务器端注册并登录。对如何对该路由使用身份验证有点困惑。
这是我的 app.js,我的客户端路由。
const App = () => {
return (
<Container maxwidh='lg'>
<BrowserRouter>
<Navbar />
<Grow in>
<Container>
<div className="content">
<Switch>
<Route path="/" exact component={Home} />
<Route path="/form" exact component={Form} />
<Route path="/auth" exact component={Auth} />
<Route path="/login" exact component={SignIn} />
</Switch>
</div>
</Container>
</Grow>
</BrowserRouter>
</Container>
);
}
export default App;
这些是我的服务器端路由。
import express from 'express';
import { getPosts } from '../controllers/posts.js'
import { createPost,updatePost,deletePost,registerPost } from '../controllers/posts.js'
const router = express.Router();
router.get('/',getPosts);
router.post('/',createPost);
router.patch('/:id',updatePost);
router.delete('/:id',deletePost);
export default router;
export const createPost = async (req,res) => {
const { title,message,selectedFile,creator,tags } = req.body;
const newPostMessage = new PostMessage({ title,tags })
try {
await newPostMessage.save();
res.status(201).json(newPostMessage );
} catch (error) {
res.status(409).json({ message: error.message });
}
}
这是来自我的 index.js 页面服务器端。
import postRoutes from './routes/posts.js'
import userRoutes from './routes/user.js'
import loginRoutes from './routes/login.js'
const app = express();
dotenv.config();
passportConfig(passport);
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json({limit: "30mb",extended: true}));
app.use(bodyParser.urlencoded({limit: "30mb",extended: true}));
app.use(cors());
app.use('/posts',postRoutes);
app.use('/auth',userRoutes);
app.use('/login',loginRoutes);
这是我的身份验证页面。
import jwt from 'jsonwebtoken';
import User from '../models/user.js';
const auth = {
ensureAuthenticated: function(req,res,next) {
if (req.isAuthenticated()) {
return next();
}
res.redirect('/');
},forwardAuthenticated: function(req,next) {
if (!req.isAuthenticated()) {
return next();
}
res.redirect('/auth');
}
}
module.exports = auth
解决方法
您正在尝试根据身份验证状态protect前端路由。因此,您可以创建一个 PrivateRoute
组件,该组件将检查用户是否已通过身份验证,当用户未通过身份验证时,它将重定向到 /login
路由:
import { Route,Redirect } from 'react-router-dom'
export default function PrivateRoute({ component: Component,...rest }) {
const { isAuthenticated } = useAuthentication()
// An example: you can create a react-hook which will provide you
// authentication details based on your implementation.
return (
<Route
{...rest}
render={props =>
isAuthenticated ? (
<Component {...props} />
) : (
<Redirect
to={{
pathname: "/login",state: { from: props.location }
// (optional) You can use this location state "from" value to redirect
// back the user from /login to the location they were trying
// to visit before authentication
}}
/>
)
}
/>
);
}
并使用上面的组件来设置路由:
...
<Switch>
<Route path="/" exact component={Home} />
<PrivateRoute path="/form" exact component={Form} /> // This is now protected
<Route path="/auth" exact component={Auth} />
<Route path="/login" exact component={SignIn} />
</Switch>
...
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。