I need to upload images from the front and that they reach the back to be able to show themselves but I have not been able to find the trick, if someone knows I would greatly appreciate it.
this is my error in the server
req files : undefined
ss ss
I'm using a react library for forms 'React-hook-form', it would be supposed that only with the field and the selected image it would be sent but when looking at the console I get undefined in the image field and in the others if it captures me the value
my front
const postCategories = async (data) => {
try {
setLoading(true);
const response = await instance.post("/categories", data);
console.log(response);
setLoading(false);
toast.success(response.data.msg);
getCategories();
setModalAdd(false);
} catch (err) {
console.log(err);
setLoading(false);
toast.error(err.response.data.msg);
}
};
console.log(data);
const bodyModalAdd = (
<Box sx={style}>
<h3 className="text-xl font-semibold">Añadir categoria</h3>
<form onSubmit={handleSubmit(postCategories)}>
<div>
<label>imagen</label>
<input
type="file"
{...register("urlImage", { required: true, })}
/>
</div>
my back
export const registarCategoria = async (req, res) => {
console.log("Intentas pasar aunque sea");
const { nombre, descripcion } = req.body;
console.log("req files : " , req.files);
console.log(nombre, descripcion);
if (nombre !== undefined && descripcion !== undefined) {
const categoriaExiste = await Categoria.findOne({
where: {
nombre: nombre,
},
});
if (categoriaExiste) {
return res.status(400).json({
msg: "Ya esta registrada la categoria ya esta registrado",
success: false,
});
}
try {
let resultadoImg = undefined;
if(req.files?.image){
resultadoImg = await uploadImage(req.files.image.tempFilePath)
}
if(resultadoImg){
await Categoria.create({
nombre,
descripcion,
urlImage : resultadoImg?.secure_url,
});
return res
.status(201)
.json({ msg: "Categoria creada correctamente", success: true });
}else{
return res.status(400).json({ msg: "No se pudo crear la categoria, falta imagen", success: false });
}
} catch (err) {
console.error(err);
}
} else {
res.status(400).json({
success: false,
msg: "Faltan datos",
});
}
};