Vue Axios query string escaping special characters

Viewed 674

I am facing a problem with Axios GET query string parameter when string includes "+" or "&" signs. I have tried using encodeURIComponent and I get

http://localhost:8001/api/data?page=1&paginate=20&term=S%2BM%20Company

When trying to query for S+M Company which is located as a value in the database table. Trying to query just a string without encoding it breaks after

http://localhost:8001/api/data?page=1&paginate=20&term=S+M.

The string is added to url from plain text field and the var is

url = url + &term=${this.search}

Any suggestions would be highly appreciated. Thanks!

2 Answers

I had the same issue and the solution was to avoid adding the url params in the axios URL but doing so in the axios config object for params. For example:

export const getRequest = (dataToSendWithSpecialCharacters) => {
  const params = new URLSearchParams(dataToSendWithSpecialCharacters);
  return axios.get('/api/data', {
    params,
  });
};

Where dataToSendWithSpecialCharacters is an object with the keys/values that will work as appended params

{ term: 'value' } // &term=S+M Company
Related