如何使用Axios将前端react.js的数据发送到后端API node.js,并将数据返回给前端

问题描述 投票:0回答:1

我尝试使用 Axios 将数据“statusId、name、startDateTime、endDateTime”从前端 React.js 发送到后端 API Node.js,并将这些数据返回到另一个页面上的前端。 我被当前的代码困住了。

这是我的前端 Holiday.js,其中数据必须发送到 API 后端。

import React, { useEffect, useState } from 'react';
import { useTheme } from '@mui/material/styles';

import {
    Container, Grid, Paper, Stack, Button, Modal, Box
} from '@mui/material';

import { useAuthContext } from "auth/useAuthContext";
import { useSettingsContext } from 'components/settings';
import 'assets/style.css';
import { CustomAvatar } from 'components/custom-avatar';
import axios from "utils/axios";
import PlaceholderDropdown from 'components/placeholder';
import DateTimeRangePicker from 'components/date-range-picker/DateTimeRangePicker'
import FormControl from '@mui/material/FormControl';
import { MakTimeWidget } from 'components/mak-time/MakTimeWidget';
import Alert from '@mui/material/Alert';


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 handleStartDateTimeChange = (newValue) => {
        setStartDateTime(newValue);
        // setStartDateTime(newValue ? newValue.toISOString() : null);
    };
    
    const handleEndDateTimeChange = (newValue) => {
        setEndDateTime(newValue);
        // setEndDateTime(newValue ? newValue.toISOString() : null);
    };

    const handleCloseModal = () => {
      setOpenModal(false);
    };

    const handleSendRequest = () => {
        // Construisez l'objet de données à envoyer
        const requestData = {
            statusId,
            name,
            startDateTime: startDateTime ? startDateTime.toString() : null,
            endDateTime: endDateTime ? endDateTime.toString() : null,
        };

        // Utilisez axios ou toute autre bibliothèque pour envoyer une requête POST au backend
        axios.post('/api/v1/holiday/send_request', requestData)
            .then(response => {
                // Gérez la réponse réussie ici
                console.log(response.data);
                setOpenModal(true); // Affichez la modal de succès
            })
            .catch(error => {
                // Gérez les erreurs ici
                console.error(error);
            });
    };

    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 ? startDateTime.toString() : null}
                                endDateTime={endDateTime ? endDateTime.toString() : null}
                                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={handleSendRequest} // Appeler la fonction lors du clic sur le bouton
                            onClick={() => {
                                // setOpenModal(true);
                                handleSendRequest();
                            }}
                            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>
    )
}

API.py

@api_view(['POST'])
@permission_classes([permissions.IsAuthenticated])
def send_request(request):
    statusId = request.data.get('statusId')
    name = request.data.get('name')
    startDateTime = request.data.get('startDateTime')
    endDateTime = request.data.get('endDateTime')
    # Fetch data from the ERP system's API
    session_id = obtain_session_id()
    url = settings.ERP_URL + '/hr_holidays/send_request'
    payload = {
        "jsonrpc": "2.0",
        "params": {
            "statusId": statusId,
            "name": name,
            "startDateTime": startDateTime,
            "endDateTime": endDateTime
        }
    }
    headers = {'Content-Type': 'application/json', 'Cookie': 'session_id={}'.format(session_id)}
    payload_json = json.dumps(payload)
    response = requests.get(url, data=payload_json, headers=headers)
    if response.status_code == 200:
        data = response.json()
        return Response(data['result']['response'], status=status.HTTP_200_OK)
    else:
        return Response({'error': 'error test'}, status=401)

前端的代码应该出现 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;

目前我的前端仅显示“Liste des congés test”。

我不知道自己做得好不好。需要一些帮助...

python reactjs node.js axios
1个回答
0
投票
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é

这个 useEffect 在挂载 AllHoliday 组件时只运行 1 次,因为依赖项是空数组。因此,当用户创建新的假期时,此 useEffect 不会再次执行,并且不会将新数据更新到 HolidayData 状态。 一些简单的方法解决它:

  • 使用状态管理器(如 redux、react-query...)保存列表假期并在有任何与假期相关的操作时更新它。
  • 创建一个状态MakHoliday组件来保存列表假期,当API POST返回成功时,请求GET更新状态。并使用 props 将列表假期传递给 AllHoliday 组件。

希望没有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.