Why am I getting a 404 (Not Found) error on my PUT request?

, it seems like the problem lies in how the form data is being sent from the ModifierCandidature.jsx component to the backend, particularly in handling file uploads.

that’s my code nodejs and react :

candidatureController.js:

import { catchAsyncErrors } from "../middlewares/catchAsyncErrors.js";
import { Candidature } from "../models/candidatureSchema.js";
import { Entreprise } from "../models/entrepriseSchema.js";
import ErrorHandler from "../middlewares/errorMiddleware.js";
import { handlePdfDeletion } from "../utils/fileUtils.js";
import path from "path";

export const addCandidature = catchAsyncErrors(async (req, res, next) => {
  const { firstName, lastName, email, phone, dob, gender, domaineentreprise, niveauetude, experience } = req.body;

  if (!req.file) {
      return next(new ErrorHandler("Le CV en PDF est requis!", 400));
  }

  const { path: pdfFullPath, mimetype } = req.file;
  const allowedFormats = ["application/pdf"];

  if (!allowedFormats.includes(mimetype)) {
      return next(new ErrorHandler("Format de fichier non supporté! Seuls les fichiers PDF sont acceptés.", 400));
  }

  if (!firstName || !lastName || !email || !phone || !dob || !gender || !domaineentreprise || !niveauetude || !experience) {
      return next(new ErrorHandler("Veuillez remplir tous les champs!", 400));
  }

  const entreprise = await Entreprise.findOne({ domaine: domaineentreprise });

  if (!entreprise) {
      return next(new ErrorHandler("Domaine d'entreprise non trouvé!", 404));
  }

  try {
      const candidatId = req.user._id;
      const pdfPath = `/files/${path.basename(pdfFullPath)}`;

      const candidature = await Candidature.create({
          firstName,
          lastName,
          email,
          phone,
          dob,
          gender,
          domaineentreprise: entreprise._id,
          niveauetude,
          experience,
          candidatId,
          pdfPath,
      });

      res.status(201).json({
          success: true,
          message: "Candidature ajoutée avec succès!",
          candidature,
      });
  } catch (error) {
      console.error("Erreur lors de l'enregistrement du PDF sur le serveur:", error);
      return next(new ErrorHandler("Échec de l'enregistrement du CV sur le serveur", 500));
  }
});

export const getCandidature = catchAsyncErrors(async (req, res, next) => {
    const candidature = await Candidature.findById(req.params.id).populate('domaineentreprise candidatId');
    
    if (!candidature) {
        return next(new ErrorHandler("Candidature non trouvée!", 404));
    }
    
    res.status(200).json({
        success: true,
        candidature,
        pdfPath: candidature.pdfPath,
    });
});

export const getCandidatures = catchAsyncErrors(async (req, res, next) => {
  const candidatures = await Candidature.find().populate('domaineentreprise candidatId');

  res.status(200).json({
    success: true,
    candidatures,
  });
});

export const updateCandidatureStatus = catchAsyncErrors(async (req, res, next) => {
  const { id } = req.params;
  let candidature = await Candidature.findById(id);
  if (!candidature) {
    return next(new ErrorHandler("Candidature non trouvée!", 404));
  }
  candidature = await Candidature.findByIdAndUpdate(id, req.body, {
    new: true,
    runValidators: true,
    useFindAndModify: false,
  });
  res.status(200).json({
    success: true,
    message: "Mise à jour de status de la candidature!",
  });
});

export const deleteCandidature = catchAsyncErrors(async (req, res, next) => {
  const candidature = await Candidature.findById(req.params.id);
  
  if (!candidature) {
    return next(new ErrorHandler("Candidature non trouvée!", 404));
  }

  try {
    // Supprimer le fichier PDF du serveur
    await handlePdfDeletion(candidature.pdfPath);

    // Assurez-vous que candidature est un document MongoDB complet avant de supprimer
    if (candidature instanceof Candidature) {
      // Supprimer la candidature de la base de données
      await candidature.deleteOne(); 
    } else {
      throw new Error("L'objet retourné n'est pas une instance de Candidature");
    }

    res.status(200).json({
      success: true,
      message: "Candidature supprimée avec succès!",
    });
  } catch (error) {
    console.error("Erreur lors de la suppression de la candidature:", error);
    return next(new ErrorHandler(`Échec de la suppression de la candidature: ${error.message}`, 500));
  }
});



export const updateCandidature = catchAsyncErrors(async (req, res, next) => {
  const { id } = req.params;
  let candidature = await Candidature.findById(id);
  
  if (!candidature) {
    return next(new ErrorHandler("Candidature non trouvée!", 404));
  }
  
  const updatedData = req.body;

  if (req.file) {
    const { path: pdfFullPath, mimetype } = req.file;
    const allowedFormats = ["application/pdf"];
    if (!allowedFormats.includes(mimetype)) {
      return next(new ErrorHandler("Format de fichier non supporté! Seuls les fichiers PDF sont acceptés.", 400));
    }
    updatedData.pdfPath = `/files/${path.basename(pdfFullPath)}`;
    await handlePdfDeletion(candidature.pdfPath); // Supprime l'ancien PDF
  }

  // Ensure candidatId is correctly set
  if (updatedData.candidatId && typeof updatedData.candidatId === 'object') {
    updatedData.candidatId = updatedData.candidatId._id || updatedData.candidatId.toString();
  }

  // Validate and handle domaineentreprise
  const entreprise = await Entreprise.findOne({ domaine: updatedData.domaineentreprise });
  if (!entreprise) {
    return next(new ErrorHandler("Domaine d'entreprise non trouvé!", 404));
  }
  updatedData.domaineentreprise = entreprise._id;

  candidature = await Candidature.findByIdAndUpdate(id, updatedData, {
    new: true,
    runValidators: true,
    useFindAndModify: false,
  });
  
  res.status(200).json({
    success: true,
    message: "Candidature mise à jour avec succès!",
    candidature,
  });
});

candidatureRouter.js :

import express from "express";
import { addCandidature, getCandidatures, getCandidature, deleteCandidature, updateCandidatureStatus , updateCandidature} from "../controller/candidatureController.js";
import { isAdminAuthenticated, isCandidatAuthenticated } from "../middlewares/auth.js";
import upload from "../middlewares/upload.js";

const router = express.Router();

router.post("/add", isCandidatAuthenticated, upload.single('pdfcv'), addCandidature);
router.get("/getall", isAdminAuthenticated, getCandidatures);
router.get("/seule/:id", isAdminAuthenticated, getCandidature);
router.delete("/seule/:id", isAdminAuthenticated, deleteCandidature);
router.put("/update/:id", isAdminAuthenticated, updateCandidatureStatus);
router.put("/modifier/:id", isAdminAuthenticated, upload.single('pdfcv'), updateCandidature);


export default router;

CandidatureDetails.jsx:

import React, { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import axios from 'axios';

const CandidatureDetails = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [candidature, setCandidature] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchCandidature = async () => {
      try {
        const { data } = await axios.get(`http://localhost:4001/api/v1/candidature/seule/${id}`, { withCredentials: true });
        setCandidature(data.candidature);
      } catch (err) {
        console.error("Erreur lors de la récupération de la candidature", err);
        setError("Erreur lors de la récupération de la candidature");
      } finally {
        setLoading(false);
      }
    };

    fetchCandidature();
  }, [id]);

  const handleEdit = () => {
    navigate(`/modifier-candidature/${id}`);
  };

  if (loading) return <div>Loading...</div>;
  if (error) return <div>{error}</div>;

  return (
    <section className="page messages">
      <h1>Détails de la Candidature</h1>
      <div className="part">
        <p><strong>Prénom:</strong> {candidature.firstName}</p>
        <p><strong>Nom:</strong> {candidature.lastName}</p>
        <p><strong>Adresse e-mail:</strong> {candidature.email}</p>
        <p><strong>Numéro de téléphone mobile:</strong> {candidature.phone}</p>
        <p><strong>Date de naissance:</strong> {new Date(candidature.dob).toLocaleDateString()}</p>
        <p><strong>Genre:</strong> {candidature.gender}</p>
        <p><strong>Poste:</strong> {candidature.domaineentreprise.domaine}</p>
        <p><strong>Niveau d'étude:</strong> {candidature.niveauetude}</p>
        <p><strong>Expérience:</strong> {candidature.experience}</p>
        <div className="cv-box">
          <a href={`http://localhost:4001${candidature.pdfPath}`} target="_blank" rel="noopener noreferrer">
            Voir le CV
          </a>
        </div>
        <button onClick={handleEdit}>Modifier</button>
      </div>
    </section>
  );
};

export default CandidatureDetails;

ModifierCandidature.jsx:

import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import axios from 'axios';

const ModifierCandidature = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [candidature, setCandidature] = useState({
    firstName: '',
    lastName: '',
    email: '',
    phone: '',
    dob: '',
    gender: '',
    domaineentreprise: '',
    niveauetude: '',
    experience: '',
    pdfPath: ''
  });
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchCandidature = async () => {
      try {
        const { data } = await axios.get(`http://localhost:4001/api/v1/candidature/seule/${id}`, { withCredentials: true });
        setCandidature(data.candidature);
      } catch (err) {
        console.error("Erreur lors de la récupération de la candidature", err);
        setError("Erreur lors de la récupération de la candidature");
      } finally {
        setLoading(false);
      }
    };

    fetchCandidature();
  }, [id]);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setCandidature({ ...candidature, [name]: value });
  };

  const handleFileChange = (e) => {
    setCandidature({ ...candidature, pdfcv: e.target.files[0] });
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    const formData = new FormData();
    for (const key in candidature) {
      formData.append(key, candidature[key]);
    }
    try {
      await axios.put(`http://localhost:4001/api/v1/candidature/modifier/${id}`, formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
        withCredentials: true
      });
      navigate(`/candidature/${id}`);
    } catch (err) {
      console.error("Erreur lors de la mise à jour de la candidature", err);
      setError("Erreur lors de la mise à jour de la candidature");
    }
  };

  if (loading) return <div>Loading...</div>;
  if (error) return <div>{error}</div>;

  return (
    <section className="page messages">
      <h1>Modifier la Candidature</h1>
      <form onSubmit={handleSubmit} className="form">
        <div className="form-group">
          <label>Prénom</label>
          <input type="text" name="firstName" value={candidature.firstName} onChange={handleChange} />
        </div>
        <div className="form-group">
          <label>Nom</label>
          <input type="text" name="lastName" value={candidature.lastName} onChange={handleChange} />
        </div>
        <div className="form-group">
          <label>Adresse e-mail</label>
          <input type="email" name="email" value={candidature.email} onChange={handleChange} />
        </div>
        <div className="form-group">
          <label>Numéro de téléphone mobile</label>
          <input type="text" name="phone" value={candidature.phone} onChange={handleChange} />
        </div>
        <div className="form-group">
          <label>Date de naissance</label>
          <input type="date" name="dob" value={candidature.dob.split('T')[0]} onChange={handleChange} />
        </div>
        <div className="form-group">
          <label>Genre</label>
          <select name="gender" value={candidature.gender} onChange={handleChange}>
            <option value="male">Homme</option>
            <option value="female">Femme</option>
            <option value="other">Autre</option>
          </select>
        </div>
        <div className="form-group">
          <label>Poste</label>
          <input type="text" name="domaineentreprise" value={candidature.domaineentreprise.domaine} onChange={handleChange} />
        </div>
        <div className="form-group">
          <label>Niveau d'étude</label>
          <input type="text" name="niveauetude" value={candidature.niveauetude} onChange={handleChange} />
        </div>
        <div className="form-group">
          <label>Expérience</label>
          <input type="text" name="experience" value={candidature.experience} onChange={handleChange} />
        </div>
        <div className="form-group">
          <label>CV</label>
          <input type="file" name="pdfcv" onChange={handleFileChange} />
        </div>
        <button type="submit">Sauvegarder</button>
      </form>
    </section>
  );
};

export default ModifierCandidature;

when i test with postman it’s work:

enter image description here

but in interface don’t:

enter image description here

Please helps me , i need solve for this problem update

The error might be due to an incorrect handling of the form data, especially the file, on the frontend. Using the browser’s developer tools to inspect the network request can help in identifying what exactly is being sent to the backend. Make sure all field names match between the frontend form and the backend controller’s expectations.

New contributor

Wiam El Mahjoubi is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật