Home > Mobile >  Axios Adds Brackets [] To Request Param
Axios Adds Brackets [] To Request Param

Time:08-24

I'm trying to add a list of items as a request parameter. When I manually write the URL like that: http://localhost:8080/api/user/book/?keyword=&page=1&pageSize=5&field=id&order=ascend&author=aziz&author=nazim, I get what I want.

However, Axios insists on adding square brackets pointlessly.

const _fetchBooks = async (params) => {
        const url = `${UrlUtil.userURL()}/book/`;

        const response = await axios.get(url, {
            params: {
                keyword: params.search,
                page: params.pagination.current,
                pageSize: params.pagination.pageSize,
                field: params.sorter?.field,
                order: params.sorter?.order,
                author: params.filter?.author,
            },
       ...
    };

Here's the result URL React trying to reach when I do filtering: http://localhost:8080/api/user/book/?keyword=&page=1&pageSize=5&field=id&order=ascend&author[]=aziz&author[]=nazim

With the brackets, I cannot go on because I get an exception:

java.lang.IllegalArgumentException: Invalid character found in the request target [/api/user/book/keyword=&page=1&pageSize=5&field=id&order=ascend&author[]=aziz&author[]=nazim ]. The valid characters are defined in RFC 7230 and RFC 3986

So, Java doesn't like the brackets.

CodePudding user response:

As @AndyRay said in the comment, it's not React doing this, its Axios. This is standard behaviour as documented by their API. You can change the way that arrays get serialized using paramsSerializer option:

const response = await axios.get(url, {
  params: {
    keyword: params.search,
    page: params.pagination.current,
    pageSize: params.pagination.pageSize,
    field: params.sorter?.field,
    order: params.sorter?.order,
    author: params.filter?.author,
  },
  paramsSerializer: { indexes: null }
});

CodePudding user response:

as I can understand your issue of Invalid character found

I suggest you to read this first:

What's valid and what's not in a URI query?

To solve this issue of using invalid characters such as "[" you need to encode the url params and to do so check this fuction:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURIComponent

Example:

const _fetchBooks = async (params) => {
        const url = `${UrlUtil.userURL()}/book/`;

        const response = await axios.get(url, {
            params: {
                keyword: params.search,
                page: params.pagination.current,
                pageSize: params.pagination.pageSize,
                field: params.sorter?.field,
                order: params.sorter?.order,
                author: encodeURIComponent(JSON.stringify(params.filter?.author)),
            },
       ...
    };

Best of luck ...

  • Related