Using React, Typescript and Nodejs. Sending form for JSON user registration. I only know how to use Formdata. How to pass the elements as JSON?

Asked

Viewed 511 times

1

Frontend

import React, { useState, FormEvent } from 'react';
import { Link, useHistory } from 'react-router-dom';
import Header from '../../components/header/header'
import './register.css'
import Image from '../../assets/images/register.svg'
import api from '../../services/api';

export default function CreateUser() {

    const history = useHistory();

    const [name, setName] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [secondPassword, setSecondPassword] = useState('');

    async function handleSubmit(event: FormEvent) {
        event.preventDefault();

        const data = new FormData();

        data.append('name', name);
        data.append('email', email);
        data.append('password', password);
        data.append('secondPassword', secondPassword);

        await api.post('register', data);

        alert('Cadastro realizado com sucesso')

        history.push('/')

    }

    return (
        <div id="register-landing">
            <Header />
            <div className="content-wrapper">
                <div className="img-div">
                    <img className="img" src={Image} alt="Register" />
                </div>
                <form onSubmit={handleSubmit} className="form" method="post" >
                    <div className="content">
                        <div className="text">
                            <h1>Cadastro</h1>
                        </div>

                        <div className="input-block">
                            <label htmlFor="name">Nome</label>
                            <input
                                id="name"
                                value={name}
                                type="text"
                                onChange={event => setName(event.target.value)}
                                placeholder="Insira seu nome..."
                            />
                        </div>
                        <div className="input-block">
                            <label htmlFor="email">Email</label>
                            <input
                                id="email"
                                value={email}
                                type="text"
                                onChange={event => setEmail(event.target.value)}
                                placeholder="Insira seu email..."
                            />
                        </div>
                        <div className="input-password-area">
                            <div className="input-password">
                                <label htmlFor="password">Senha</label>
                                <input
                                    id="password"
                                    type="password"
                                    value={password}
                                    onChange={event => setPassword(event.target.value)}
                                />
                            </div>

                            <div className="input-password">
                                <label htmlFor="secondPassword">Confirmar Senha</label>
                                <input
                                    id="secondPassword"
                                    type="password"
                                    value={secondPassword}
                                    onChange={event => setSecondPassword(event.target.value)}
                                />
                            </div>
                        </div>
                        <div className="buttons">
                            <Link to="/" className="cancel-button">
                                Cancelar
                        </Link>
                            <button type="submit" className="register-button">
                                Cadastrar
                        </button>
                        </div>

                    </div>
                </form>
            </div>
        </div>
    )
}

Usercontroller

import { Request, Response } from 'express'
import { getRepository } from 'typeorm'
import User from '../models/user'
import * as Yup from 'yup';

class UserController {
    async protected(req: Request, res: Response) {
        const getUser = getRepository(User)
        return res.json(getUser)
    }
    async store(req: Request, res: Response) {
        const repository = getRepository(User)
        const {
            name,
            email,
            password,
            secondPassword,
            phone,
            about,
            joinDate
        } = req.body

        const userExists = await repository.findOne({ where: { email } })

        if (userExists) {
            return res.sendStatus(409)
        }

        const data = {
            name,
            email,
            password,
            secondPassword,
            phone,
            about,
            joinDate
        }

        const schema = Yup.object().shape({
            name: Yup.string().required('Nome obrigatório'),
            email: Yup.string().required('Email obrigatório'),
            password: Yup.string().required('Senha obrigatória'),
            secondPassword: Yup.string().required('Senha de confirmação obrigatória'),
            phone: Yup.string(),
            about: Yup.string(),
            joinDate: Yup.string()
        })

        await schema.validate(data, { 
            abortEarly: false })

        const user = repository.create(data)
        await repository.save(user)

        return res.status(201).json(user);
    }
}

export default new UserController();

2 answers

1


Opa Andre!

To send a json, you must put the Header Content-type as 'application/json' and the body you send in a string format.

In his example, data will be a simple object, and in your api.post method you can switch to body with JSON.stringify(data), so the object will be in the right format for request.

Would that way:

async function handleSubmit(event: FormEvent) {
    event.preventDefault();

    const data = {
       name,
       email,
       password,
       secondPassword
    };

    await api.post('register', data).then((response) => {
       alert('Cadastro realizado com sucesso')   
       history.push('/')
    }).catch((err)=>{
       // handle exception error
    })

}

Stringify Fetch API

  • Thank you so much for your help, I spent a few days cracking my head

  • 1

    If you solved the problem, check as a solution to help the next devs ( and help me too haha! )

0

First on the server express you must pass this setting to it to work with the format json:

app.use(express.json())

In his controller you can access this data in the format json thus:

app.post('/exemplo', (request, response) => {
  const { atributoJson, outroAtributo } = request.body
  
  // seu código

  return response.status(201).json(objetoJson)
})

In his frotend React, if you’re using Axios lib to http, you need to configure the content format of the request as json, thus:

const http = axios.create({
  baseURL: 'http://...',
  timeout: 15000,
  headers: { "Content-Type": "application/json" }
});

or

axios.post('https://example.com', formularioJson, { headers: {"application/json"}})

With this setting just pass a json object as content of the request that will work fine

  • Thank you so much for your help

  • If solved otherwise post here to help other people or mark this answer as solution if it also solves your problem. Hug

Browser other questions tagged

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