0

I am having difficulty sending an array of Id numbers from React state, through Node/Express, then eventually to MongoDB.

The main difficulty is how to send an array from React to the server. Once I have it there in a usable array form, I believe I know how to query MongoDB using an array.

I have been trying to do this mainly with a GET method and have been unsuccessful using req.params or req.query. I have tried this with several versions of string templates, and using what the Axios docs say as well as many other answers on stack overflow, none have been successful.

I have also tried a couple of versions of a PUT request and also with no success.

The array of Ids already exists in props.completedJobs:

In React:

  useEffect(() => {
    const fetchData = async () => {
      let completedJobsArray =  props.completedJobs;
      let json = JSON.stringify(data);
      let getData = {jsonData: json};
      const result = await axios('/api/brief/brief-array/' + getData);
      setData(result.data);
    };
    fetchData();

  }, []);

In Express app:


app.use("/brief", briefRouter);

then in the router:

router.get("/brief-array/:briefArray", briefController.brief_findArrayById);  

then the function:

exports.brief_findArrayById = async (req, res) => {
  try {
    // console.log("req.body: ", req.body);
    // console.log("req: ", req);
    // console.log("req.query: ", req.query);
    // console.log("req.params: ", JSON.stringify(req.params.briefArray));

    const briefs = await GWJob.find({"_id": {$in: ["5d1297512c68bc49060bce7b", "5d1297092c68bc49060bce7a"] } }); 
    res.json(briefs);
  } catch (err) {
    res.json({ message: err });
  }
}

The MongoDB query works with the hard-coded IDs, but cannot get any of the above versions of console.logs to display any value other than undefined or "object object".

I am also unable to query the database using an array through Postman.

I expect to send 1 or more id numbers in an array to MongoDB, and receive those documents back to React on the front end. Any help with sending an array from state in React through Node/Express is much appreciated! Thank you.

6
  • Are you using bodyparser or cookieparser? Commented Aug 17, 2019 at 0:10
  • Currently bodyparser.urlencoded with extended: true Commented Aug 17, 2019 at 0:33
  • Then im sure is all about your request, not very familiar with axios, but i think you need to stringify your json or send it as object, but im not sure how are you handling your api routing, have you tried: ```axios('/api/brief/brief-array', getData);? Commented Aug 17, 2019 at 0:40
  • Thank you, yes I believe I have tried stringify and axios('/api/brief/brief-array', getData) as above. The axios documentation seems to be incomplete on this. I'm happy to use another method to send an array if you know how to do it. Commented Aug 17, 2019 at 0:44
  • 1
    I just want to help, but unfortunately I always use 'fetch' like this: fetch(url, { headers: { 'Content-Type': 'application/json; charset=utf-8' }, method: 'POST', body: JSON.stringify({ data, }) }) I think is a fast way to test! Commented Aug 17, 2019 at 1:03

2 Answers 2

1

You are sending Long string through the URL which is a limited length (~2047 char), the safe away to accomplish what you are trying to do to use a post or put method and send the list in the body.

Example:

useEffect(() => {
    const fetchData = async () => {
      let completedJobsArray =  props.completedJobs;
      const result = await axios({
                         method: 'post',
                         url: '/brief-array',
                         data: completedJobsArray
                        });
      setData(result.data);
    };
    fetchData();

  }, []);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, If I do it this way the console log shows req.data to be undefined, and req.body to be an empty {}. Same if I change data: to body: This is the code: ``` useEffect(() => { const fetchData = async () => { let completedJobsArray = props.completedJobs; const result = await axios ({ method: 'POST', url: '/api/brief/brief-array', data: completedJobsArray }); setData(result.data); }; fetchData(); }, []); ```
0

Another attempt, still returning undefined. If anyone has links to a thorough resource on sending/receiving data I would much appreciate it. I always have spent days trying to get one of these to work, until I started using Axios, but if I need to go beyond what I can do with Axios I am back to square one. Many thanks.

useEffect(() => {
    const fetchData = async () => {    
    let completedJobsArray = props.completedJobs;
    let queryData = {completedJobsArray};

    const settings = {
      method: 'POST',
      headers: { 'Content-Type': 'application/json; charset=utf-8'},
      body: JSON.stringify(queryData)
    };

    try {
      const fetchResponse = await fetch(`/api/brief/brief-array`, settings);
    const returnedData = await fetchResponse.json();
    setData(returnedData);
    } catch (error) {
      console.error("error: ", error);
    }
  }
  fetchData();
}, []);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.