问题描述
因此,我有一个登录按钮,该按钮链接到一个表单,该表单可以在用户登录时在服务器上正常运行,但是,我还有一个演示按钮,其中包含预填充的信息,当我单击该按钮时,我会获取数据和哈希参数必需的错误。
import React from 'react';
import './loginContent.css';
import { useHistory } from 'react-router-dom'
import { Button,TextField,Dialog,DialogTitle,makeStyles,Box,Container,CssBaseline,Typography,Grid,Link } from '@material-ui/core';
import * as yup from 'yup'
import { Formik,Form } from 'formik'
import { loginUser } from '../../services/userServices'
import { usedispatch } from 'react-redux'
import { fetchUser } from '../../actions/user_actions'
let LoginSchema = yup.object().shape({
email: yup.string().email().required("This field is required"),password: yup.string().min(6,"Password needs to be at least 6 characters").required("This field is required")
})
const useStyles = makeStyles((theme) => ({
paper: {
marginTop: theme.spacing(1),display: 'flex',flexDirection: 'column',alignItems: 'center',},form: {
width: '100%',marginTop: theme.spacing(1),submit: {
margin: theme.spacing(3,2),backgroundColor: "green"
},submit_demo: {
margin: theme.spacing(3,backgroundColor: "lightgreen",color: "black"
},title: {
padding:'5px',marginLeft:'6px',cursor:"pointer"
},root: {
width: '100%','& > * + *': {
marginTop: theme.spacing(2),}
}));
function LoginContent(props) {
const dispatch = usedispatch()
const { open,setLogin,setSignUp } = props;
const history = useHistory();
const switchSignup = (event) => {
setLogin(false)
setSignUp(true)
}
const loginSuccess = () => {
setLogin(false)
}
const classes = useStyles()
const handleDemo = async (e) => {
e.preventDefault()
const demoLogin = await loginUser({
email: 'demo@gmail.com',passsword: 'aaaaaa'
})
console.log("demologin",demoLogin)
window.localStorage.setItem(
'loggedUser',JSON.stringify(demoLogin))
dispatch(fetchUser({
email: 'demo@gmail.com',passsword: 'aaaaaa'
}))
loginSuccess()
}
return (
//closing the overlay container and opening a new one.
//---> uses open state built in to control whether it renders or not from other modules
<Dialog className="login" aria-labelledby="simple-dialog-title" open={open} onClose={(event) => setLogin(false)}>
<DialogTitle className={classes.title} onClick={() => setLogin(false)}>X</DialogTitle>
<Container component="main" maxWidth="xs" spacing={5}>
<CssBaseline />
<div className={classes.paper}>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<Formik
initialValues={{
email:'',password:''
}}
validationSchema={LoginSchema}
onSubmit={async (values) => {
try{
const logUser = await loginUser({
...values
})
window.localStorage.setItem(
'loggedUser',JSON.stringify(logUser)
)
dispatch(fetchUser(values))
loginSuccess()
// history.push('/home')
// history.go(0)
}catch(e){
console.error("nopE",e.message)
window.alert("Incorrect Credentials - please try again")
}
}}
>
{({errors,handleChange,touched}) => (
<Form className={classes.form}>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
onChange={handleChange}
autoFocus
error={errors.email && touched.email}
helperText={errors.email && touched.email ? errors.email : null}
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
autoFocus
onChange={handleChange}
error={errors.password && touched.password}
helperText={errors.password && touched.password ? errors.password : null}
/>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
<Button
fullWidth
variant="contained"
color="primary"
className={classes.submit_demo}
onClick={handleDemo}
>
Demo Login
</Button>
<Box b={8}>
<Grid container spacing={5}>
<Grid item xs>
</Grid>
<Grid item>
<div className="switchLink">
<Link onClick={switchSignup}>
{"Don't have an account? Sign Up"}
</Link>
</div>
</Grid>
</Grid>
</Box>
</Form>
)}
</Formik>
</div>
</Container>
</Dialog>
);
}
export default LoginContent
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
const loginRouter = require('express').Router()
const User = require('../model/user')
const { response } = require('express')
loginRouter.post('/',async(request,response) => {
const body = request.body
console.log("body recieved",body)
const user = await User.findOne({email: body.email})
console.log("user",user)
const passwordCorrect = user === null ? false
: await bcrypt.compare(body.password,user.passwordHash,function(err,result) {
if(err) console.log("something happened:",err)
console.log("works well:",result)
})
if(!(user && passwordCorrect)) {
return response.status(401).json({
error: 'invalid username or password'
})
}
// use this information for creating the token,will go in jwt payload
const userForToken = {
email: user.email,id: user._id
}
const token = jwt.sign(userForToken,process.env.SECRET)
// response.status(200).send({token,email: user.email,firstName: user.firstName,lastName: user.lastName})
response.status(200).send({email: user.email,lastName: user.lastName,id: user._id,bookings: user.bookings})
})
module.exports = loginRouter
import axios from 'axios'
let token = null;
const setToken = newToken => {
token = `bearer ${newToken}`
}
const loginUser = async credentials => {
console.log("credentials received",credentials)
const response = await axios.post('/login',credentials)
return response.data
}
const signUpUser = async ( userData ) => {
try {
const res = await axios.post('/',userData);
return res.data;
} catch (e) {
throw new Error(`status ${e.response.status}: ${e.response.data.error}`)
}
}
const getCurrentUser = () => {
return JSON.parse(window.localStorage.getItem('loggedUser'))
}
const logout = () => {
window.localStorage.removeItem('loggedUser')
}
export { loginUser,signUpUser,getCurrentUser,logout }
对不起,这是我的第一个个展。
编辑:
这是我在检查服务器代码时得到的,这是我使用常规登录功能时得到的
body recieved { email: 'demo@gmail.com',password: 'aaaaaa' }
user {
bookings: [],_id: 5fa70e8c9cbc3cd6679108e6,firstName: 'John',lastName: 'G.',email: 'demo@gmail.com',passwordHash: '$2b$10$J9Ivj.IcX.jzAhfES4ZSF.jUxeO9Co.aiEtpFXw9a.Rjw7TPu9uF6',__v: 0
}
POST /login 200 107 - 218.580 ms
body recieved { email: 'demo@gmail.com',__v: 0
}
POST /login 200 107 - 95.098 ms
[nodemon] restarting due to changes...
[nodemon] starting `node server/index.js`
这是我使用演示功能的时候
Server running on port 4000
connected to MongoDB
hello
GET /home 200 7118 - 207.099 ms
body recieved { email: 'demo@gmail.com',passsword: 'aaaaaa' }
user {
bookings: [],__v: 0
}
something happened: Error: data and hash arguments required
at Object.compare (/Users/jonathangetahun/Desktop/Computer Science/rustic_bnb/node_modules/bcrypt/bcrypt.js:208:17)
at /Users/jonathangetahun/Desktop/Computer Science/rustic_bnb/server/controllers/loginRouter.js:13:24
at processticksAndRejections (internal/process/task_queues.js:97:5)
at runNextTicks (internal/process/task_queues.js:66:3)
at processImmediate (internal/timers.js:429:9)
at process.topLevelDomainCallback (domain.js:137:15)
works well: undefined
POST /login 401 40 - 28.043 ms
更详细地讲,当我删除bcrypt回调函数进行比较时,出现此错误:
POST /login 500 1160 - 22.220 ms
Error: data and hash arguments required
at Object.compare (/Users/jonathangetahun/Desktop/Computer Science/rustic_bnb/node_modules/bcrypt/bcrypt.js:208:17)
at /Users/jonathangetahun/Desktop/Computer Science/rustic_bnb/node_modules/bcrypt/promises.js:29:12
at new Promise (<anonymous>)
at Object.module.exports.promise (/Users/jonathangetahun/Desktop/Computer Science/rustic_bnb/node_modules/bcrypt/promises.js:20:12)
at Object.compare (/Users/jonathangetahun/Desktop/Computer Science/rustic_bnb/node_modules/bcrypt/bcrypt.js:204:25)
at /Users/jonathangetahun/Desktop/Computer Science/rustic_bnb/server/controllers/loginRouter.js:13:24
at processticksAndRejections (internal/process/task_queues.js:97:5)
at runNextTicks (internal/process/task_queues.js:66:3)
at processImmediate (internal/timers.js:429:9)
at process.topLevelDomainCallback (domain.js:137:15)
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)