0

how are u doing?

Its funny because i have 2 forms, one for instruments and the other one for user. The instruments one works perfect (so i can discard that its a entry point configuration problem) When i receive the info, the req body always come empty.

Front React

import React, { Component }from 'react';
import "./register.css"
import Axios from "axios";

class Register extends Component {
state = {
    nombre: "",
    apellido: "",
    password: ""
}

changeHandler = e => {
        this.setState({ [e.target.name]: e.target.value });
}

submitHandler = e => {
    e.preventDefault();
    
    const formData = new FormData();
    formData.append("nombre", this.state.nombre);
    formData.append("apellido", this.state.apellido);
    formData.append("password", this.state.password);

    Axios
    .post('http://localhost:5000/usuarios/guardar', formData)
    .then(response => {
        console.log(response)
        })
    .then(data => console.log(data))
        .catch(error => {
            console.log(error)
        })

    console.log("formData2", formData)
}
    
    render(){
        
        const {nombre,apellido,password} = this.state
        
        return(
            <section className="forms-container margin-sections">
            <form onSubmit={this.submitHandler} method="POST" id="register">
                    <fieldset>
                        <input type="text" placeholder="Nombre" name="nombre" value={nombre} className="input" onChange={this.changeHandler}/>
                    </fieldset>
                    <fieldset>
                        <input type="text" placeholder="Apellido" name="apellido" value={apellido} className="input" onChange={this.changeHandler}  />
                    </fieldset>
                    <fieldset>
                        <input type="password" placeholder="Contraseña" name="password" value={password} className="input" onChange={this.changeHandler} />
                    </fieldset>
                <fieldset>
                    <button className="button-login" type="submit">Enviar</button>
                </fieldset>
                </form>
        </section>
)}
}

export default Register;

Backend Express

const db = require("../database/models");

const main = {
post: async (req, res) => {
    try{
        
        let data = req.body;
        
        
        let usuario = {
            nombre: String(data.nombre),
            apellido: String(data.apellido),
            password: String(data.password),
        
        }

        console.log(usuario);

        return console.log("llegue bien perreke");
        
    }catch(e){
        console.log(e);
    }
},
}


module.exports = main;

Entry Point

// ************ Require's ************

const express = require('express');
const path = require('path');
const app = express();
const cors = require('cors');
const bodyParser = require('body-parser');


// ************ Data Configuration ************

app.use(bodyParser.json())
app.use(express.urlencoded({ extended: false}));
app.use(express.json())

//CORS
app.use(cors());

// ************ Servidor ************

app.set("port", process.env.PORT || 5000);
app.listen(app.get("port"), () => console.log("Server start in 
http://localhost:"+app.get("port")));



// ************ Acceso Publico ************

app.use(express.static(path.resolve(__dirname, "../public/uploads/instruments"))); // 
Necesario para los archivos estáticos en el folder /public

// ************ API's ************

const apiInstrumentos = require("./routes/apiInstrumentos");

app.use("/instrumentos", apiInstrumentos)


// ************ Router Define ************

const instrumentRouter = require("./routes/instrumentos.js");

app.use("/", instrumentRouter);

const users = require("./routes/user");

app.use("/usuarios", users);

Console Example between Instrument Axios Post Req Body and User Axios Post Req Body

Server start in http://localhost:5000
[Object: null prototype] {  
nombre: 'Prueba Info',    
fabricante: 'Prueba Info',
precio: '120000',
categoria: '2',
descuento: '0',
precioDescuento: '0',     
texto: 'Prueba Info',     
fecha: '2022-05-18',      
modelo: 'Modelo',
color: 'Color',
images: '[object File]'   
}
{ nombre: 'undefined', apellido: 'undefined', password: 'undefined' }
  • To handle `multipart/form-data` request bodies, you need a different middleware like [Multer](https://github.com/expressjs/multer#usage) – Phil May 03 '22 at 23:41
  • Does this answer your question? [Access file upload formData in Express](https://stackoverflow.com/questions/65655500/access-file-upload-formdata-in-express) – Phil May 03 '22 at 23:43
  • Nop, because i dont have a problem with files, the problem its that i cant get any information, always i get undefined – Juan Segundo Martínez May 04 '22 at 03:22
  • You missed the point. It's not about files, it's about using `FormData` and thus `multipart/form-data`. None of the middleware you're currently using handles those request payloads – Phil May 04 '22 at 03:23
  • If you want to avoid using `FormData` since you're not uploading files, see [this answer](https://stackoverflow.com/a/67087324/283366). – Phil May 04 '22 at 03:26
  • Yeah you were rigth, the problem was that i hadnt used multer – Juan Segundo Martínez May 04 '22 at 05:43

1 Answers1

-1

change encoding middleware to:

app.use(express.urlencoded({ extended: true}));

the extended: true precises that the req.body object will contain values of any type instead of just strings.

Lucas Rissi
  • 112
  • 3
  • I tryed that but i have the same error, anyways the instrument form brings me imgs and other types of values besides strings, thanks for the comment! – Juan Segundo Martínez May 03 '22 at 23:21
  • The `express.urlencoded()` middleware does **not** handle `multipart/form-data` requests, no matter what configuration you pass to it – Phil May 04 '22 at 03:26