简体   繁体   中英

React - Axios null value in post request body

I'm new using axios and I have a problem with a post request. I pass an array to the request body to the backend, but It's null when the query is executed.

These are my Components: (The request It's in "getDriversFromARace Function )

import React, { useState, useEffect,useLayoutEffect} from "react";
import "../../styles/race.css";
import "../../App.css"
import axios from "axios";
import {useParams} from 'react-router-dom';
import DriversForm from "../Drivers/DriversForm";

const RaceResultsForm = () => {
    const [raceResults,setRaceResults] = useState([]);
    const [driversFromRace,setDriversFromRace] = useState([]);
    const {raceId} = useParams();

    const getRaceResults = async() => {
        await axios.post(`http://localhost:5000/api/race-results/${raceId}`)
        .then(res => res.data)
        .then(res => setRaceResults(res));
    }
    useLayoutEffect(() => {
        getRaceResults();
    }, []);



    console.log(driversFromRace);

    return(
        <>
            <DriversForm raceResults={raceResults}/>
        </>
    )
};
export default RaceResultsForm;
import React, { useState, useEffect,useLayoutEffect} from "react";
import "../../styles/race.css";
import "../../App.css"
import axios from "axios";

const DriversForm = ({raceResults}) => {
    const [driversFromRace,setDriversFromRace] = useState([]);
    const driversId = raceResults.map(driver => driver.driverId)

    const getDriversFromARace = async() => {
        await axios.post("http://localhost:5000/api/driver-from-race",{
            driverId:driversId
        })
        .then(res => res.data)
        .then(res => setDriversFromRace(res));
    }
    useEffect(() => {
        getDriversFromARace();
    },[]);

    return (
        <>
            <div className="container">
                <div className="card">
                    <div className="card-body">
                        <div className="card-header">
                            <h3 className="card-title">
                                <b>Choose a Driver</b>
                            </h3>
                        </div>
                        <form>
                            <div className="select-countries">
                                <select className="custom-select" name="country" id="country">
                                    {driversFromRace.map(driver => (
                                    <option key={driver.driverId} value={driver.driverId}>{driver.forename} {driver.surname}</option>
                                    ))}
                                </select>
                                <span className="custom-arrow"></span>
                            </div>
                            <button className="btn btn-danger btn-flat mt-5">Search</button>
                        </form>
                    </div>
                </div>
            </div>
        </>
    )
};
export default DriversForm;

Controller from backend:

const Driver = require('../models').drivers;
const Sequelize = require('sequelize');

module.exports = {

    getDriversFromARace(req,res){
        return Driver
            .findAll({
                attributes:{exclude:['createdAt','updatedAt']},
                where:{
                    driverId:{
                        [Sequelize.Op.in]:req.body.driverId
                    }
                }
            })
            .then(driver => {
                res.status(200).json(driver);
            })
            .catch(error => {
                res.status(500).send({message:error.message});
            })
    }
}

The component is rendered when I click in "Link" button:

<Link to={`/race-results-form/${row.original.raceId}`}>
   <button type="button" className="btn btn-success btn-see-results-races">
        See Results
   </button>
</Link>

When the component is rendered, the query executes, but It's getting NULL on the body. Why is that?

在此处输入图像描述

Thank you in advance.

EDIT

I put a console.log with the variable "driversId" and the IDs are there but its printed 3 times before print the IDs.

在此处输入图像描述

I suspect that your backend is missing the necessary middleware for parsing JSON. You can verify this by console logging req.body in the controller route. If req.body is an empty object, this is your problem.

A couple of other notes:

  1. I would get rid of the driversId variable altogether. As you can see in the console log, that.map is executing each time the component renders. Since that variable is only actually being used in that post request, just make the object in the POST request look like

    { driverId: raceResults.map(driver => driver.driverId) }

  2. Since you aren't sending a data object in the RaceResultsForm API request, you should probably just be utilizing a GET request rather than POST.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM