How to send data from frontend react.js to backend API node.js using Axios and return back this data to frontend

I”m try to send data ‘statusId, name, startDateTime, endDateTime’ from frontend react.js to backend API node.js using Axios and return back this data to my frontend on another page.
I’m stuck with my current code.

Here is my frontend holiday.js where the data must go to backend.

export default function MakHoliday() {
    const theme = useTheme();
    const { user } = useAuthContext();
    const { themeStretch } = useSettingsContext();
    const [statusId, setStatusId] = useState();
    const [name, setName] = useState();
    const [startDateTime, setStartDateTime] = useState(null);
    const [endDateTime, setEndDateTime] = useState(null);
    const [openModal, setOpenModal] = useState(false);
    const [isButtonDisabled, setIsButtonDisabled] = useState(true);

    useEffect(() => {
        setIsButtonDisabled(!(statusId && name && startDateTime && endDateTime));
    }, [statusId, name, startDateTime, endDateTime]);

    const sendHolidayRequest = () => {
        axios.post('/api/v1/holiday/send_holiday_request', {
            statusId,
            name,
            startDateTime,
            endDateTime,
        })
        .then(response => {
            console.log(response.data);
            // Gérez le succès, peut-être mettez à jour l'interface utilisateur ou affichez un message de réussite
        })
        .catch(error => {
            console.error(error);
            // Gérez l'erreur, affichez un message d'erreur à l'utilisateur
        });
        console.log({statusId});
        console.log({name});
        console.log({startDateTime});
        console.log({endDateTime});
    };
    

    const handleStartDateTimeChange = (newValue) => {
        setStartDateTime(newValue);
    };
    
    const handleEndDateTimeChange = (newValue) => {
        setEndDateTime(newValue);
    };

      const handleCloseModal = () => {
        setOpenModal(false);
      };
    return (
        <FormControl sx={{ m: 1, width: '100%', mt: 3 }}>
            <Grid>
                <Grid sx={{ mt: 3 }}>
                    <Paper sx={{paddingBottom: '30px'}}>
                        <Grid sx={{
                            padding: theme.spacing(2)
                        }}>
                            <Stack sx={{
                                marginX: theme.spacing(3),
                                padding: theme.spacing(0, 0, 2, 1),
                                ...theme.typography.h4,
                                borderBottom: () => `solid 1px ${theme.palette.divider}`
                            }}>Take holiday</Stack>
                        </Grid>
                        <Container maxWidth={themeStretch ? false : 'xl'}>
                                <MakTimeWidget />
                                    <Grid sx={{ display: 'flex', padding: theme.spacing(2), justifyContent: 'center', alignItems: 'center' }} item xs={12} lg={0} md={0} sm={12}>
                                        <CustomAvatar key={48}
                                            alt={user.first_name}
                                            src={user.profile}
                                            sx={{ width: 80, height: 80 }} />
                                    </Grid>
                                    <Grid sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center' }} item xs={12} lg={0} md={0} sm={12}>
                                            <Grid sx={{ ...theme.typography.body1 }}>{user.first_name}</Grid>
                                    </Grid>
                                    <Grid sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', paddingBottom: theme.spacing(6), }} item xs={12} lg={0} md={0} sm={12}>
                                            <Grid sx={{ ...theme.typography.caption }}>{user.job_name}</Grid>
                                    </Grid>

                                <PlaceholderDropdown
                                    setStatusId={setStatusId}
                                    setName={setName}
                                />

                            <DateTimeRangePicker 
                                startDateTime={startDateTime}
                                endDateTime={endDateTime}
                                handleStartDateTimeChange={handleStartDateTimeChange}
                                handleEndDateTimeChange={handleEndDateTimeChange}
                            />
                            <Button
                            variant="contained"
                            sx={{ 
                                width: '30%', 
                                display: 'flex', 
                                justifyContent: 'center', 
                                alignItems: 'center', 
                                padding: theme.spacing(2), 
                                margin: 'auto', 
                                marginTop: '30px',
                            }}
                            onClick={sendHolidayRequest}
                            disabled={isButtonDisabled}
                            >
                                send request
                            </Button>

                            {/* Modal pour afficher l'Alert */}
                            <Modal
                              open={openModal}
                              onClose={handleCloseModal}
                              aria-labelledby="modal-title"
                              aria-describedby="modal-description"
                            >
                              <Box sx={{
                                position: 'absolute',
                                top: '50%',
                                left: '50%',
                                transform: 'translate(-50%, -50%)',
                                width: 400,
                                p: 4,
                              }}>
                              <Alert severity="success">Your request is sended</Alert>
                              </Box>
                            </Modal>
                        </Container>
                    </Paper>
                </Grid>
            </Grid>
        </FormControl>
    )
}

here is my backend API.py

# API to get all holidays
@api_view(['POST'])
def send_holiday_request(request):
    data = request.data
    serializer = serializers.holidaySerializer(data=data)

    if serializer.is_valid():
        # Faites quelque chose avec les données (par exemple, enregistrez-les dans la base de données)
        serializer.save()
        return Response({'message': 'Holiday request received successfully'}, status=status.HTTP_201_CREATED)
    else:
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializers.py

from . import models

# holiday 
class holidaySerializer(serializers.ModelSerializer):
    class Meta:
        model = models.holiday
        fields = ['statusId', 'name', 'startDateTime', 'endDateTime']

my models.py

class holiday(models.Model):
    # Champs du modèle
    statusId = models.IntegerField()
    name = models.CharField(max_length=255)
    startDateTime = models.DateTimeField()
    endDateTime = models.DateTimeField()

    # Autres champs que vous pourriez ajouter en fonction de vos besoins

    class Meta:
        verbose_name_plural = "Holiday - SW"

    def __str__(self):
        return self.name

urls.py

urlpatterns = (
    path('v1/holiday/send_holiday_request', api.send_holiday_request, name="send_holiday_request"),
)

and the frontend allholiday.js where the data need to return back.

// AllHoliday.js
import React, { useEffect, useState } from 'react';
import axios from 'axios';

const AllHoliday = () => {
  const [holidayData, setHolidayData] = useState([]);

  useEffect(() => {
    axios.get('api/v1/holiday')
      .then(response => {
        setHolidayData(response.data);
      })
      .catch(error => {
        console.error(error);
        // Gérez l'erreur, affichez un message d'erreur à l'utilisateur
      });
}, []); // Exécuté une fois lorsque le composant est monté


  // Affichage des données de congé
  return (
    <div>
      <h1>Liste des congés test</h1>
      <ul>
        {holidayData.map(holiday => (
          <li key={holiday.statusId}>
            <p>Nom: {holiday.name}</p>
            <p>Début: {holiday.startDateTime}</p>
            <p>Fin: {holiday.endDateTime}</p>
            {/* Ajoutez d'autres champs en fonction de votre structure de données */}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default AllHoliday;

currently just the ‘Liste des congés test’ appears on my frontend.

also an error message in my console.

index.js:14 
AxiosError {message: 'Request failed with status code 404', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …}
code
: 
"ERR_BAD_REQUEST"
config
: 
{transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}
message
: 
"Request failed with status code 404"
name
: 
"AxiosError"
request
: 
XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}
response
: 
{data: '<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta char…liday/send_holiday_request</pre>\n</body>\n</html>\n', status: 404, statusText: 'Not Found', headers: AxiosHeaders, config: {…}, …}
stack
: 
"AxiosError: Request failed with status code 404\n    at settle (http://localhost:3000/static/js/bundle.js:169962:12)\n    at XMLHttpRequest.onloadend (http://localhost:3000/static/js/bundle.js:168676:66)"
[[Prototype]]
: 
Error

Looking information on the net but as I’m new can’t resolve my problem myself…

Leave a Comment