2021年4月4日星期日

Fetching param.id data from front to backend - React / Node / Express

I am trying to return a user list on a component from my backend and I am having trouble passing my userID param back. I am using useEffect to pull the data from Redux then call an action on the component with what I think is the declared param. The correct userID is being passed correctly as far as I can see however I think the error is occuring when the route is passed the param.

In my action how should I pass the param of the userID that I want to get the data for? I have console.log the param.id/param.userID/userID etc. In the component I have the user.userID (from useSelector) however in the action folder I don't know how to pass it to the backend.

Also in the backend do I always have to set my params as id? can these have the same name as the value on the front-end such as 'userID'? I can only seem to get the backend Postman calls working with :id.

![image|690x249](upload://acH5vA0ni6ClNNGOWwGE7mHhfYH.png)

component

const user = useSelector(state => state.auth.user);        const [userDiveLog, setUserDiveLog] = useState({          user: [],          userDiveLogList: [],            expanded: false      })        // get access to dispatch      const dispatch = useDispatch();        useEffect(() => {          dispatch(fetchUserDiveLog(user.userID));      }, []);  

action

// pulls the user dive log  export function fetchUserDiveLog(params, credentials, diveLogUserList){      return function(dispatch){          return axios.get("http://localhost:5002/api/divelog/userdiveloglist/" + params.userID)              .then(({data}) => {                  dispatch(userDiveLogList(data));              });      };  }  

Backend

route

//  return an individual dive log      app.get('/api/divelog/userdiveloglist/:userID', controller.userDiveLog);  

controller

exports.userDiveLog = (req, res, params, userID) => {        try {          const userID = req.params.userID            diveLog.findAll({              include: {all: true},              where: {diverUserNumber: userID}          })              .then(diveLog => {                  const userDiveLogList = [];                  for (i = 0; i < diveLog.length; i++) {                      userDiveLogList.push(diveLog[i].dataValues);                  }                  if (!userDiveLogList) {                      return res.status(404).send({message: "No dive logs belonging to this user"});                  }                  res.status(200).send({                      data: userDiveLogList                  })              })      } catch(err) {              res.status(500).send({                  message: "Error retrieving dive log belonging to user id= " + id              });          }  };  
https://stackoverflow.com/questions/66947902/fetching-param-id-data-from-front-to-backend-react-node-express April 05, 2021 at 11:26AM

没有评论:

发表评论