I tried to log into the system with the email and username I previously registered; however, I’m not able to log in successfully. I also attempted to debug it with Visual Studio Code, but I didn’t find any errors while debugging. There were no errors in the browser console either. I will provide the code that I believe is crucial for understanding the context
Entrar.js
import { useEffect, useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import styles from './Entrar.module.css';
const Entrar = () => {
const navigate = useNavigate();
useEffect(() => {
const token = localStorage.getItem('token');
if (token) {
navigate('/');
}
}, [navigate]);
const [dados, setDados] = useState({
email: '',
senha: '',
});
const [erro, setErro] = useState("");
const handleMudar = ({ currentTarget: input }) => {
setDados({ ...dados, [input.name]: input.value });
};
const handleEnviar = async (e) => {
e.preventDefault();
try {
const url = 'http://localhost:5555/autenticar';
const { data: resultado } = await axios.post(url, dados);
localStorage.setItem('token', resultado.token);
window.location = "/";
} catch (erro) {
if (
erro.response && erro.response.status >= 400 &&
erro.response.status <= 500
) {
setErro(erro.response.data.message);
}
}
}
return (
<div className={styles.entrar_container}>
<div className={styles.entrar}>
<div className={styles.left}>
<form onSubmit={handleEnviar} className={styles.form}>
<h1>Entrar</h1>
<input
type="email"
placeholder="Email"
name='email'
onChange={handleMudar}
value={dados.email}
required
className={styles.input}
/>
<input
type="password"
placeholder="Senha"
name='senha' // Changed to 'senha' from 'password'
onChange={handleMudar}
value={dados.senha}
required
className={styles.input}
/>
{erro && <div className={styles.erro_msg}>{erro}</div>}
<div className={styles.button_container}>
<button type="submit" className={styles.entrar_btn}>
Entrar
</button>
<Link to="/entrar/cadastrar">
<button className={styles.novo_aqui_btn}>
Novo Aqui?
</button>
</Link>
</div>
</form>
</div>
</div>
</div>
);
}
export default Entrar;
autenticarRotas.js
/* Importa os módulos necessários */
const express = require('express');
const { Usuario } = require('../models/usuario');
const Joi = require('joi');
const bcrypt = require('bcrypt');
const autenticarRotas = express.Router();
autenticarRotas.post('/', async (request, response) => {
try {
const { error } = validar(request.body);
if (error)
return response.status(400).send(error.details[0].message);
/* Verifies if exist a user with the email */
const usuario = await Usuario.findOne({ email: request.body.email });
/* if doesn't exist returns a message */
if (!usuario)
return response.status(400).send({ message: "Usuário não encontrado" });
/* Verifies if the password or email is correct */
const senhaValida = await bcrypt.compare(
request.body.senha, usuario.senha
);
if (!senhaValida)
return response.status(400).send({ message: "Senha ou email incorreto" });
const token = usuario.generateAuthToken();
response.status(200).send({ dados: token, message: "Login efetuado com sucesso" });
} catch (error) {
return response.status(500).send({ message: "Erro interno do servidor (autetica rota)" });
}
});
/* Cria um validação de dados usando joi*/
const validar = (dados) => {
const schema = Joi.object({
email: Joi.string().email().required().label("Email"),
senha: Joi.string().required().label("Senha"),
});
return schema.validate(dados);
};
/* Exporta a route */
module.exports = autenticarRotas;
2
Answers
Check the network tab from your dev tools. Do you see the request you are trying to do? This might give you a hint about your problem. Another thing you can do is console log the entire axios response, maybe you are getting something you are not expecting there.
I think you didn’t import axios