Search code examples
node.jsexpressnext.jsaxiosmulter

I don't understand why the POST request is returning an axios 404 error


The axios post request keeps returning a 404 error even though the route seems to be correct. The put request also stops wrking when I add the POST request but goes back to work normally after deleting the post request. It was working fine at first so I may have made something wrong but I can't find the mistake anywhere. Any help would be greatly appreciated.

This is the handleSubmit function:

  
 const handleSubmit = async e => {
        e.preventDefault()

   const formData = new FormData();
        formData.append('avatar', archivoImagen);
        
 try {

            const datosActualizados = {
                nombre,
                apellido,
                usuarioID,
                email,
                descripcion,
                fechaNacimiento,   
             };          
            
            const { data } = await clienteAxios.put(`/usuarios/perfil/${auth._id}`, datosActualizados)        
           
            const response = await clienteAxios.post(`/usuarios/perfil/avatar`, formData)
                console.log(response)      


            setAlertaVisible(true)
            setAlerta({
                msg: data.msg,
                error: false,
            })
            setTimeout(() => {
                setAlertaVisible(false)
            }, 3000);
        } catch (error) {

And this is the routes file I've created:



import express from 'express';
import checkAuth from '../middleware/checkAuth.js';
import { upload } from '../middleware/multer.js';


import {
    registrar,
    autenticar,
    confirmar,
    olvidePassword,
    comprobarToken,
    nuevoPassword,
    perfil,
    editarPerfil,
    usuarioIdDisponible,
} from '../controllers/usuarioController.js'

const router = express.Router();


router.post("/", registrar)
router.post("/login", autenticar)
router.get("/verificar-usuario", usuarioIdDisponible)
router.get('/confirmar/:token', confirmar)
router.post('/olvide-password', olvidePassword)
router.route('/olvide-password/:token')
    .get(comprobarToken)
    .post(nuevoPassword)
router.get('/perfil', checkAuth, perfil)
router.put('/perfil/:id', editarPerfil);
router.post('/perfil/avatar', upload.single('avatar'));





export default router;
 

I would like both the POST and PUT requests to be fired when when the handleSubmit function is triggered, so users can update the profile data through the PUT request, and also send the avatar image to a local folder in the project through the POST request


Solution

  • Adding a a route handler after upload.single() actually worked!!

    I ended up using this:

    router.post('/perfil/avatar', upload.single('avatar'), (req, res)=> {
    res.sendStatus(202)
    console.log(req.file)
    

    });

    Thank you very much Phil. You've saved my life!