简体   繁体   中英

Vue Axios query string escaping special characters

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!

There is a built in helper for that:

https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/URLSearchParams

Use it like:

const data = {
  queryOne: 'value1',
  queryTwo: 'value2'
};

const myParams = new URLSearchParams(data);
myParams.toString()

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM