Axios 获取参数数组

Fab*_*ner 2 javascript vue.js axios

我用 axios 创建了一个 get 请求:

this.$axios.get('/cidade/',{
          params: {
            q: result,
          }
        })
        .then((response) => {
          this.cidades = response.data;
        })
        .catch(function (error) {
          // handle error
          // eslint-disable-next-line
          console.log(error);
        })
        .then(function () {

          // always executed
        });
Run Code Online (Sandbox Code Playgroud)

但我的结果是一个数组 [123asdas1,asdasd2312] 并且当 axios 执行请求时,他创建了该 url:

http://localhost:8081/cidade/?q[]=5b9cfd0170607a2e968b0a1e&q[]=5b9cfd0170607a2e968b0a1d
Run Code Online (Sandbox Code Playgroud)

所以可以从 q 参数中删除 [] 吗?如何?

tks

Dec*_*oon 6

在编写一个字段具有多个值的查询字符串时(即,如果它是一个数组),则没有标准说明它必须如何在查询字符串中编码,但是大多数 Web 服务器接受以下语法:

http://localhost:8081/cidade/?q[]=value1&q[]=value2
Run Code Online (Sandbox Code Playgroud)

这就是 axios 默认使用它的原因。检查您的 Web 服务器以查看它是否正确地将参数作为数组读取。

如果您想强制以其他方式对其进行编码,只需将数组转换为您想要的任何格式的字符串并将其作为单个值发送:

this.$axios.get('/cidade/', {
  params: {
    q: JSON.stringify(result)
  }
})
Run Code Online (Sandbox Code Playgroud)
http://localhost:8081/cidade/?q=[value1,value2]
Run Code Online (Sandbox Code Playgroud)

[]字符可能是百分比编码的。)

通常,这种语法无法区分 string"[value1,value2]"和 array [value1, value2],因此 Web 服务器将不得不选择其中之一。同样,这完全取决于您的 Web 服务器。