Answer the question
In order to leave comments, you need to log in
I have an authorization and user registration form, How to transfer to another page upon successful data entry?
Hello guys! I need help I have a user registration and authorization form,
when registering I get all the user data userd id, password, and so on.
When a user logs in, he finds this data in the database that was entered during registration, but I don’t know how to transfer to another page, I’m new to this.
This is the form page
import React, {useEffect, useState, useContext } from "react";
import {BrowserRouter as Router} from 'react-router-dom'
import {useHttp} from "../hooks/http.hook";
import {useMessage} from "../hooks/message.hook";
import {AuthContext} from "../context/authContext";
export const AuthPage = () => {
const auth = useContext(AuthContext);
const message = useMessage()
const {loading, request, error, clearError} = useHttp()
const [form, setForm] = useState({
email: '', password: ''
})
useEffect(() => {
message(error)
clearError()
},[error, message, clearError])
const changeHandler = event => {
setForm({...form, [event.target.name]: event.target.value })
}
const registerHandler = async () => {
try {
const data = await request('/api/auth/register', 'POST', {...form})
message(data.message)
} catch (e){}
}
const loginHandler = async () => {
try {
const data = await request('/api/auth/login', 'POST', {...form})
auth.login(data.token, data.userId)
} catch (e){}
}
return(
<Router>
<div className="wrap-home">
<div className="texthome">
<h1>Authorization</h1>
<div className="line3"></div>
</div>
<div className="form">
<form action="" method="">
<label htmlFor="email">Email</label>
<input type="text" id="email" name="email" placeholder=" Email" onChange={changeHandler}/>
<label htmlFor="email">Password</label>
<input type="password" id="password" name="password" placeholder=" Your Password" onChange={changeHandler}/>
<button placeholder="Sing up" onClick={registerHandler} disabled={loading}>Sing up</button>
<button placeholder="Log in" onClick={loginHandler} disabled={loading}>Log in</button>
</form>
</div>
</div>
</Router>
)
const {Router} = require('express')
const bcrypt = require('bcryptjs')
const config = require('config')
const jwt = require('jsonwebtoken')
const {check, validationResult} = require('express-validator')
const User = require('../models/user')
const router = Router()
router.post(
'/register',
[
check('email', 'Неккорректный email').isEmail(),
check('password', 'Минимальная длинна 6 символов')
.isLength({min: 6})
],
async(req, res ) => {
try {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array(),
message: 'Некорректные данные при регистрации!'
})
}
const {email, password} = req.body
const candidate = await User.findOne({ email })
if (candidate){
return res.status(400).json({message:'Такой пользователь есть'})
}
const hashedPassword = await bcrypt.hash(password, 12)
const users = new User ({email, password:hashedPassword})
await users.save()
res.status(201).json({message:'Пользователь создан!'})
} catch (e){
res.status(500).json({message:'Что-то пошло не так'})
}
})
router.post(
'/login',
[
check('email', 'Введите корректный email!').normalizeEmail().isEmail(),
check('password', 'Введите пароль').exists()
],
async(req, res ) => {
try {
const errors = validationResult(req)
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array(),
message: 'Некорректные данные при в входе в систему!'
})
}
const {email, password} = req.body,
users = await User.findOne({ email })
if (!users){
return res.status(400).json({message:'Пользователь не найден!'})
}
const isMatch = await bcrypt.compare(password, users.password)
if (!isMatch ){
return res.status(400),json({message:'Неверный пароль или Логин, попробуйте снова!'})
}
const token = jwt.sign(
{ userId: users.id },
config.get('jwtSecret'),
{expiresIn: '1h'}
)
res.json({ token, userid: users.id })
} catch (e){
Console.log('catch', e.message)
res.status(500).json({message:'Что то пошло не так'})
}
})
module.exports = router
import React from 'react'
import {Switch, Route, Redirect} from 'react-router-dom'
import {LinksPage} from './pages/LinksPage'
import {HomePage} from './pages/HomePage'
import {DetailPage} from './pages/DetailPage'
import {AuthPage} from './pages/AuthPage'
export const useRoutes = isAuthenticated => {
if (isAuthenticated){
return(
<Switch>
<Route path="/links" exact>
<LinksPage />
</Route>
<Route path="/HomePage" exact>
<HomePage />
</Route>
<Route path="/detail/:id">
<DetailPage />
</Route>
<Redirect to="/" />
</Switch>
)
}
return (
<Switch>
<Route path="/AuthPage" exact>
<AuthPage />
</Route>
<Redirect to="/HomePage"/>
</Switch>
)
}
import {useState, useCallback, useEffect } from 'react'
const storageName = 'userData'
export const useAuth = () => {
const [token, setToken] = useState(null)
const [userId, setUserId] = useState(null)
const login = useCallback((jwtToken, id) => {
setToken(jwtToken)
setUserId(id)
localStorage.setItem(storageName, JSON.stringify({
userId: id, token: jwtToken
}))
},[])
const logout = useCallback(() => {
setToken(null)
setUserId(null)
localStorage.removeItem(storageName)
}, [])
useEffect(() => {
const data = JSON.parse(localStorage.getItem(storageName))
if (data && data.token){
login(data.token, data.userId)
}
}, [login])
return [login, logout, token, userId]
}
Answer the question
In order to leave comments, you need to log in
Either server-side 3xx responses or client-side windows.location are responsible for transitions
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question