0
Hello, I’m trying to create a user, but when sending the post method with the user data I get one 400 Bad Request server, the problem is that the server is not understanding the data, in the error appears as if all fields were missing.
Follow prints and code:
import { Request, Response } from 'express';
import { getRepository } from 'typeorm';
import * as Yup from 'yup';
import User from '../models/users';
import UserView from '../views/users_view';
export default {
async login(request: Request, response: Response) {
// const userReposity = getRepository(User);
// const {
// userName,
// userPassword,
// } = request.body;
},
async createUser(request: Request, response: Response) {
const {
userName,
userPassword,
access_level,
} = request.body;
const userReposity = getRepository(User);
const data = {
userName,
userPassword,
access_level
}
const schema = Yup.object().shape({
userName: Yup.string().required('Nome obrigatório'),
userPassword: Yup.string().required('Senha obrigatória'),
access_level: Yup.string().required('Nível de acesso obrigatório'),
})
await schema.validate(data,
{ abortEarly: false }
);
const user = userReposity.create(data);
await userReposity.save(user);
return response.status(201).json(user);
}
}
Code of the front end:
import api from '../services/api'
import '../styles/pages/login-page.css';
export default function Login() {
const history = useHistory();
const [name, setName] = useState('');
const [password, setPassword] = useState('');
async function handleSubmitLogin(event: FormEvent){
event.preventDefault();
const data = new FormData();
data.append('userName', name);
data.append('userPassword', password);
await api.post('usercreate', data);
history.push('/dashboard');
}
return (
<div className="containerLogin">
<Link to="/app">
<FiArrowLeft size={32} color="#FFF" className="button-GoBack" />
</Link>
<div className="container-inputs">
<form className="container-inputsLogin" onSubmit={handleSubmitLogin}>
<h1 className="text-login">Login</h1>
<div className="input-blockLogin">
<label htmlFor="name">
<FiUser size={32} color="#FFF" className="icon-input" />
</label>
<input
id="name"
value={name}
onChange={event => setName(event.target.value)}
placeholder="Nome de usúario" />
</div>
<div className="input-blockLogin">
<label htmlFor="password">
<FiKey size={32} color="#FFF" />
</label>
<input
className="input-password"
id="password"
value={password}
onChange={event => setPassword(event.target.value)}
placeholder="Senha"
type="password" />
</div>
<button className="confirm-button" type="submit">
ENTRAR
<FiArrowRight size={28} color="#141414" className="button-arrow"/>
</button>
</form>
</div>
</div>
)
}