简体   繁体   English

如何正确使用 axios 参数与 arrays

[英]How to correctly use axios params with arrays

How to add indexes to array in query string?如何在查询字符串中向数组添加索引?

I tried send data like this:我试过这样发送数据:

axios.get('/myController/myAction', { params: { storeIds: [1,2,3] })

And I got this url:我得到了这个 url:

http://localhost/api/myController/myAction?storeIds[]=1&storeIds[]=2&storeIds[]=3

So, I should to get this url:所以,我应该得到这个 url:

http://localhost/api/myController/myAction?storeIds[0]=1&storeIds[1]=2&storeIds[2]=3

What I should add in my params options to get this url?我应该在我的参数选项中添加什么来获得这个 url?

You can use paramsSerializer and serialize parameters with https://www.npmjs.com/package/qs您可以使用paramsSerializer并通过https://www.npmjs.com/package/qs序列化参数

axios.get('/myController/myAction', {
  params: {
    storeIds: [1,2,3]
  },
  paramsSerializer: params => {
    return qs.stringify(params)
  }
})

无需添加更多库并使用 ES6,您可以编写:

axios.get(`/myController/myAction?${[1,2,3].map((n, index) => `storeIds[${index}]=${n}`).join('&')}`);

Thanks so much the answer from Nicu Criste , for my case, the API requires params like this:非常感谢Nicu Criste的回答,就我而言,API 需要这样的参数:

params: {
  f: {
    key: 'abc',
    categories: ['a','b','c']
   },
  per_page: 10
}

Method is GET and this API requires the format is: API?f[key]=abc&f[categories][]=a&f[categories][]=b... So I assigned the paramsSerializer of axios like this:方法是 GET,这个 API 需要的格式是: API?f[key]=abc&f[categories][]=a&f[categories][]=b...所以我给 axios 的 paramsSerializer 赋值是这样的:

config.paramsSerializer = p => {
      return qs.stringify(p, {arrayFormat: 'brackets'})
    }

In my case, I use ES6 array function.就我而言,我使用 ES6 数组函数。 array element make querystring use reduce function.数组元素使查询字符串使用reduce函数。 Object array also works.对象数组也可以。

const storeIds = [1,2,3]
axios.get('some url', {
  params: {
    storeIds: storeIds.reduce((f, s) => `${f},${s}`)
  }
})

In my case, I am using someting like this就我而言,我正在使用这样的东西

const params = array.map((v)=>{
            return `p=${v}&`
        })

Only concat params.join('') to the URL where you get data:params.join('')连接到您获取数据的 URL:

`url_to_get?${params.join('')`

In my back-end in ASP.net I receive this在我的 ASP.net 后端我收到这个

[FromUri] string [] p

I rewrote the existing paramSerializer shipped in axios.我重写了 axios 中现有的 paramSerializer。 The following snippet does the same serialization while putting indices between square brackets.以下代码片段在将索引放在方括号之间时执行相同的序列化。 I tried qs but it is not compatible with my python connexion backend (for JSON string parameters).我试过 qs 但它与我的 python connexion 后端不兼容(用于 JSON 字符串参数)。

const rcg = axios.create({
    baseURL: `${url}/api`,
    paramsSerializer: params => {
        const parts = [];

        const encode = val => {
            return encodeURIComponent(val).replace(/%3A/gi, ':')
                .replace(/%24/g, '$')
                .replace(/%2C/gi, ',')
                .replace(/%20/g, '+')
                .replace(/%5B/gi, '[')
                .replace(/%5D/gi, ']');
        }

        const convertPart = (key, val) => {
            if (val instanceof Date)
                val = val.toISOString()
            else if (val instanceof Object)
                val = JSON.stringify(val)

            parts.push(encode(key) + '=' + encode(val));
        }

        Object.entries(params).forEach(([key, val]) => {
            if (val === null || typeof val === 'undefined')
                return

            if (Array.isArray(val))
                val.forEach((v, i) => convertPart(`${key}[${i}]`, v))
            else
                convertPart(key, val)
        })

        return parts.join('&')
    }
});

I got using "paramSerializer" a bit confuse.我使用“paramSerializer”有点困惑。 Before looking for the "right way" to use axios with array querystring on Google, I did following and got working:在寻找在 Google 上使用带有数组查询字符串的 axios 的“正确方法”之前,我做了以下操作并开始工作:

var options = {};
var params = {};
for(var x=0;x<Products.length;x++){
   params[`VariableName[${x}]`] = Products[x].Id;
}
options.params = params;

axios.get(`https://someUrl/`, options)...

It is going to create querystring parameters like:它将创建查询字符串参数,例如:

VariableName[0]=XPTO,VariableName[1]=XPTO2

which the most webservers expected as array format大多数网络服务器预期为数组格式

I know that this approach is not very good and I don't know the downsides it may have, but i tried this and it worked:我知道这种方法不是很好,我不知道它可能有哪些缺点,但是我尝试了这个并且它奏效了:

before making the request, prepare the params:在发出请求之前,准备好参数:

  let params = '?';

  for (let i = 0; i < YOUR_ARRAY.length; i++) {  // In this case YOUR_ARRAY == [1, 2, 3]
    params += `storeIds=${YOUR_ARRAY[i]}`;  // storeIds is your PARAM_NAME
    if (i !== YOUR_ARRAY.length - 1) params += '&';
  }

And then make the request like so:然后像这样发出请求:

axios.get('/myController/myAction' + params)

This answer is inspired by @Nicu Criste's answer .这个答案的灵感来自@Nicu Criste 的答案

But might be not related to the posted question.但可能与发布的问题无关。

The following code was used to generate the query params with repetitive keys which had been supplied with an object array.以下代码用于生成带有重复键的查询参数,这些键已随对象数组一起提供。

Note: If you are a developer with bundlephobia , use the following approach with care: as with UrlSearchParams support varies on different browsers and platforms .注意:如果您是具有bundlephobia的开发人员,请谨慎使用以下方法:因为UrlSearchParams支持在不同的浏览器和平台上有所不同。

const queryParams = [{key1: "value1"}, {key2: "value2"}]

axios.get('/myController/myAction', {
  params: queryParams,
  paramsSerializer: params => {
    return params.map((keyValuePair) => new URLSearchParams(keyValuePair)).join("&")
  }
})

// request -> /myController/myAction?key1=value1&key2=value2

In React I needed to use axios with a params in array.在 React 中,我需要将 axios 与数组中的参数一起使用。 This was query param:这是查询参数:

"fields[0]=username&fields[1]=id&populate[photo][fields][0]=url&populate[job][fields][1]=Job"

to send with axios, for that I installed by CLI用 axios 发送,为此我通过 CLI 安装

npm install qs Read more about qs npm install qs阅读有关 qs 的更多信息

and declared并宣布

const qs = require('qs');

after
const query = qs.stringify({
fields: ['username', 'id'],
populate: {
photo: {
fields: ['url']
},
job: {
fields: ['Job']
}
}
}, {
encodeValuesOnly: true
});

and finally I called the axios like this:最后我这样调用 axios:
axios.create({
baseURL: "http://localhost:1337/api/",
}).get( ` /users?${query} ` ) // this parameter show all data }).get( ` /users?${query} ` ) // this parameter show all data
.then((response) => console.log(response.data))
.catch((err) => {
setError(err);
});

Basically, reading from docs https://axios-http.com/docs/req_config基本上,阅读文档https://axios-http.com/docs/req_config
paramsSerializer is an optional function, which we should use if the default serialization of params done by axios is not as expected. paramsSerializer是一个可选的 function,如果axios完成的params的默认序列化不符合预期,我们应该使用它。

We can use serialization libraries (which I feel is best approach) to serialize in the params in the paramsSerializer function as per our needs.我们可以使用序列化库(我认为这是最好的方法)根据我们的需要在 paramsSerializer function 中的参数中进行序列化。
Let's see an example.Suppose params is like...让我们看一个例子。假设参数就像......

{
      params: {
        delay: 1,
        ar:[1,2,3]
      }
}

then you will get queryString like this ?delay=1&ar[]=1&ar[]=2&ar[]=3 when you make the request, but you might want like this ?delay=1&ar[0]=1&ar[1]=2&ar[2]=3那么当你发出请求时你会得到这样的查询字符串?delay=1&ar[]=1&ar[]=2&ar[]=3 ,但你可能想要这样?delay=1&ar[0]=1&ar[1]=2&ar[2]=3

so in order to get query string as per our format.所以为了按照我们的格式获取查询字符串。 we can use qs https://www.npmjs.com/search?q=qs library我们可以使用qs https://www.npmjs.com/search?q=qs
and serialize our params in the paramsSerializer function as below并在paramsSerializer function 中序列化我们的参数,如下所示

{
      method: "GET",
      params: {
        delay: 1,
        ar:[1,2,3]
      },
      paramsSerializer: (params) => {
        return qs.stringify(params,{
          encodeValuesOnly: true
          });
      }
},

This work it for me:这对我有用:

axios.get("/financeiro/listar",{
        params: {
          periodo: this.filtro.periodo + "",
          mostrarApagados: this.filtro.mostrarApagados,
          mostrarPagos: this.filtro.mostrarPagos,
          categoria: this.filtro.categoria,
          conta: this.filtro.conta
        }
      })

在此处输入图像描述

Use JSON.stringify to bind array in string and then send arrat in params. 使用JSON.stringify将数组绑定为字符串,然后以参数形式发送arrat。

let storeIds: [1,2,3];
axios.get('/myController/myAction', { params: { storeIds: JSON.stringify(storeIds) })

This was better for me:这对我来说更好:

axios.get('/myController/myAction', {
params: { storeIds: [1,2,3] + ''}

}) })

In my case, there was already jQuery implemented into my codebase.就我而言,我的代码库中已经实现了 jQuery。 So I just used the predefined method.所以我只是使用了预定义的方法。

jQuery.param(Object)

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

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