400 Bad request on express and typeorm server

Asked

Viewed 187 times

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>
    )

}

Print do erro no insomnia

1 answer

3


You do not need to create a formData for this, just pass the fields directly on the request body. Example:

await api.post('usercreate', { userName: name, userPassword: password });

Or if you want to work with formData you need to configure for your service api to receive request with type content: "multipart/form-data"

Follow an example of this setting using the library axios:

const http = axios.create({
  baseURL: 'https://example.com',
  timeout: 15000,
  headers: { "Content-Type": "multipart/form-data" }
});

or

axios.post('https://example.com', form, { headers: {"Content-Type": "multipart/form-data"}})

Now in the API part you can use the library Multer to help you work with formData if you didn’t want to use the json format

Browser other questions tagged

You are not signed in. Login or sign up in order to post.