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
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.
CodePudding user response:
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(","),
...