PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 14, 2022

[FIXED] How to send array of querystring with react and axios?

 October 14, 2022     axios, node.js, query-string, react-redux, reactjs     No comments   

Issue

I am trying to use the query string with axios to filter some data from the backend, I can do it with the backend api but I was struggling when it came to the frontend with react on how to send the array of query string to the backend. Here is my backend endpoint with array of query string params, it is working fine when I tested with postman.

localhost:3040/v2/feedback/filter/average-ratings?receiver=62c2dd106742823a69f98dac&receiver=62aec70881e46a4794b3a424

enter image description here

Here is my frontend code that I tried to send the request but return the error

export const filterAverageRating = async (receiver) => {
  console.log('Receiver ID', receiver); //['62c2dd106742823a69f98dac', '62aec70881e46a4794b3a424']
  const accessJWT = sessionStorage.getItem('accessJWT');
  const config = {
    headers: {
      'Content-Type': 'application/json',
      Authorization: accessJWT,
    },
  };
  const { data } = await axios.get(
    ENDPOINT_URL + 'filter/average-ratings',
    config,
    { params: { receiver } }
  );

  return data;
};

it return receiver is undefined from the backend, it means that there is something went wrong with query string in axios.


Solution

You can use paramsSerializer for axios. This way your requested query param will keep appending its key e.g. ?query=one&query=two&query=three

const { data } = await axios.get(ENDPOINT_URL + "filter/average-ratings", {
  ...config,
  params: receiver,
  paramsSerializer: (params) =>
    qs.stringify(params, { arrayFormat: "repeat" }),
});

Hint: Your params are part of axios config while performing get requests.

Alternatively, if your API accepts comma separated queries as an array e.g. query=one,two,three you can simply use this without needing paramsSerializer

  ...
  params: receiver.join(","),
  ...


Answered By - sm3sher
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing