简体   繁体   English

Vue Axios 查询字符串 escaping 特殊字符

[英]Vue Axios query string escaping special characters

I am facing a problem with Axios GET query string parameter when string includes "+" or "&" signs.当字符串包含“+”或“&”符号时,我遇到了 Axios GET 查询字符串参数的问题。 I have tried using encodeURIComponent and I get我试过使用 encodeURIComponent ,我得到了

http://localhost:8001/api/data?page=1&paginate=20&term=S%2BM%20Company 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.尝试查询作为值位于数据库表中的 S+M 公司时。 Trying to query just a string without encoding it breaks after试图只查询一个字符串而不编码它会在之后中断

http://localhost:8001/api/data?page=1&paginate=20&term=S+M. 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 并且 var 是

url = url + &term=${this.search} 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 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 . 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其中 dataToSendWithSpecialCharacters 是一个 object ,其键/值将作为附加参数工作

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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