'file appear in req.body but it dosent in req.file,

How are u doing? I cant get the file from req.file, i have encType, multer middleware, and all the necessary stuff to work, but it dosent, so plz give me a hand! Thanks you

Front

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

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

changeHandler = e => {
    if (e.target.name === "file") {
        this.setState({ [e.target.name]: e.target.files });
    } else {
        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);
    formData.append("file", this.state.file);


    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("file", this.state.file)

}
    
    render(){
        
        const {nombre,apellido,password} = this.state
        
        return(
            <section className="forms-container margin-sections">
            <form onSubmit={this.submitHandler} method="POST" id="register" encType="multipart/form-data">
                    <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>
                        <input type="file" name="file" className="input" onChange={this.changeHandler} id="user-photo" />
                    </fieldset>
                <fieldset>
                    <button className="button-login" type="submit">Enviar</button>
                </fieldset>
                </form>
        </section>
    )}
 }

export default Register;

Back Route

const express = require('express');
const router = express.Router();
const path = require("path");
const fs = require("fs");
const user = require("../controllers/user");
const multer = require("multer");



// ************ Multer ************

const dest = multer.diskStorage({
destination: function (req, file, cb) {
    let dir = path.resolve(__dirname,"../../public/uploads","users",             
 String(req.body.nombre).trim().replace(/\s+/g, ''))
    if (!fs.existsSync(dir)){
        fs.mkdirSync(dir);
    }
    cb(null, dir)
},
filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now()+ path.extname(file.originalname))
}
})

const upload = multer({storage:dest});


// ************ Routes ************


router.post('/guardar', upload.single("") , user.post)

module.exports = router;

Back Controller

const main = {
post: async (req, res) => {
    try{
        
        let data = req.body;
        
        let file = req.file;

        console.log("holaa2", req);

        console.log("holaa2", file, req.files);

        
        // let usuario = {
        //     nombre: String(data.nombre),
        //     apellido: String(data.apellido),
        //     password: String(data.password),
        //     // image: file.file
        // }

        // let usuarios = await db.Users.create(usuario)

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

Console.log of Req in User controller

holaa2 undefined undefined (first one is req.file and the second one is req.files) when i use upload.any() it appear a empty [] with the name of files, opposite case with upload.single("file"), where nothing happend.

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: true}));
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"))); //     

// ************ 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);

Please give me a feedback, its the third time that i ask for a solution a nobody helps me, im very stucked because i cant find where is the problem! Thx you



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source