Rupali Singh
Rupali Singh

Reputation: 151

How to ensure that axios encode my space to %20 and keep $ as it is?

this is a part of my url url -

foo?$filter=fooNum eq '1234567'

when sending the axios request, axios encodes it to - foot%24filter=fooNum+eq+%27123456%27

Now my backend doesnt understand "+" and %24 as $. Also axios automatically eliminates the '?' which I need in the url.

Expected url should be this - foo?$filter=fooNum%20eq%20%271234567%27

I have tried using paramsSerializer, endcodeComponentURI, but nothing works. I am using axios version - 1.1.3

Upvotes: 2

Views: 2532

Answers (1)

Phil
Phil

Reputation: 164970

Using paramsSerializer is the way to go. Run each parameter key / value through encodeURIComponent() and replace %24 with $.

Make sure you use the params option when making your requests to take advantage of the serialiser.

console.log("Axios version", axios.VERSION);

const sapClient = axios.create({
  baseURL: "https://echo.zuplo.io/", // replace with your base URL
  paramsSerializer: {
    encode: (param) => encodeURIComponent(param).replaceAll("%24", "$"),
  },
});

sapClient
  .get("/foo", {
    params: {
      $filter: "fooNum eq '1234567'",
    },
  })
  .then(({ data: { url } }) => {
    console.log("requested URL:", url); // this just shows the requested URL
  });
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Upvotes: 4

Related Questions